I'm working with the built-in Django User model. This is my serializers.py:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'password', 'email', )
This is my view:
class HomePageView(TemplateView):
template_name = "home.html"
def get_context_data(self, **kwargs):
context = super(HomePageView, self).get_context_data(**kwargs)
return context
class user_list(APIView): #called when I go to the /CMS/users URL
"""
List all users, or create a new user.
"""
serializer_class = UserSerializer
def get(self, request):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
def post(self, request):
serializer = UserSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
and this is home.html:
<html ng-app="notesApp">
<body ng-controller="MainCtrl as ctrl">
<form ng-submit="ctrl.add()" name="myForm">
<label>Username</label>
<input type="text" name="uname" ng-model="ctrl.user.username" required>
<label>Password</label>
<input type="password" name="pwd" ng-model="ctrl.user.password" required>
<label>Email</label>
<input type="email" name="mail" ng-model="ctrl.user.email" required>
<input type="submit" value="Submit" ng-disabled="myForm.$invalid">
</form>
</div>
and this is the JS:
angular.module("notesApp", [])
.controller("MainCtrl", ["$http", function($http) {
var self = this;
self.users = {}
var fetchUsers = function() {
// the line below gets the list of all users
return $http.get("/CMS/users").then(function(response) {
self.users = response.data;
}, function(errResponse) {
console.error("Error while fetching users.");
});
};
fetchUsers();
self.add = function() {
$http.post("/CMS/users", self.user).then(fetchUsers);
console.log("User clicked submit with ", self.user);
};
}]);
I used the form and successfully created a user (I used a valid username, email and password). I tried to recreate a user using a username which already exists. When I clicked the "Submit" button on the form, it returned a 400 error in the log (as predicted) because Django does not allow a new user to be created if the username already exists. Now, django.admin.models.AbstractModel returns an error which says that the username already exists:
class AbstractUser(AbstractBaseUser, PermissionsMixin):
"""
An abstract base class implementing a fully featured User model with
admin-compliant permissions.
Username, password and email are required. Other fields are optional.
"""
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, digits and '
'@/./+/-/_ only.'),
validators=[
validators.RegexValidator(r'^[\w.@+-]+$',
_('Enter a valid username. '
'This value may contain only letters, numbers '
'and @/./+/-/_ characters.'), 'invalid'),
],
error_messages={
'unique': _("A user with that username already exists."),
})
Is there a way for me to display the "A user with that username already exists" with AngularJS on the front-end?
Edit: I changed the self.add() function to this:
self.add = function() {
$http.post("/CMS/users", self.user)
.error(function(data, status, headers, config) {
console.log(data);
})
.then(fetchUsers);
};
and then when I tried to create a user using a username which already exists, this gets logged:
Object {username: Array[1]}
username: Array[1]
0: "This field must be unique."
length: 1
__proto__: Array[0]
__proto__: Object