How to display Django form errors using AngularJS?

I am 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', )

      

It's my opinion:

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 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 the user using an already existing username. When I clicked the submit button on the form, it returned a 400 error in the log (as predicted) because Django does not allow new user creation if the username already exists. Now django.admin.models.AbstractModel returns an error that says 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 to show "User with this username already exists" with AngularJS on the frontend?

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 that already exists, it gets registered:

Object {username: Array[1]}
   username: Array[1]
     0: "This field must be unique."
     length: 1
     __proto__: Array[0]
  __proto__: Object

      

+3


source to share


1 answer


$http.post("/CMS/users", self.user).then(fetchUsers).catch(function(response){
  //here you can manipulate the response from the server and display the message
});

      

Actually .. in the documentation for $ http you should handle:

.error(function(data, status, headers, config) {
  // called asynchronously if an error occurs
  // or server returns response with an error status.
 })

      

The answer to your question is below: it depends. If the result is always something like:, {property:[]}

then you can do:



for(prop in data){
  if(data.hasOwnProperty(prop)){
     var messages = data[prop];
     // now you have the messages array and you can display them.
  }
}

      

Otherwise, if the result is different, you are stuck handling each case.

Edit:

Using hasOwnProperty is best practice to ensure that we don't grab properties from the prototypical inheritance chain: more details - basically make sure you're not grabbing an inherited property

+2


source







All Articles