MinedBP
MinedBP

Reputation: 31

How to JSON parse using form.errors.as_json() in Django return JsonResponse(data)

In Django, I tried using form.errors.as_json() to get all form errors and here is sample json data strings.

{"password2":[{"message": "This password is too short. It must 
contain at least 8 characters.","code":"password_too_short"}]}

I wanted to loop and get all under "message" key in json so I can use it to notify the user after ajax call.

Thanks

Upvotes: 1

Views: 2014

Answers (2)

Jota
Jota

Reputation: 737

The correct answer should be:

return HttpReponse(form.errors.as_json(), status=400).

In the AJAX call you can get the content doing:

`$.post("{% url 'your_url'%}", your_payload).done(function(data) {
     do_something();        
 }).fail(function(xhr){
     // Here you can get the form's errors and iterate over them.
     xhr.responseText();            
 });`

You are sending a 200 HTTP response, that it is wrong, you should return a 400 HTTP response (Bad request), like Django do without AJAX forms.

Upvotes: 0

MinedBP
MinedBP

Reputation: 31

Anyways, I just resolved my issue and just wanted to share what I did.

views.py

if form.is_valid():
    ...
else:
    # Extract form.errors
    errMsg= None
    errMsg = [(k, v[0]) for k, v in form.errors.items()]

return JsonResponse(errMsg)

Ajax Event

$.ajax({
            method: "POST",
            url: '\your_url_here',
            data: $form.serialize(),
            cache: false,
            dataType: "json",
            beforeSend: function(){
                //Start displaying button's working animation
                //Do some button or loading animation here...
                }
            },
            success: function(jResults)
            {
                //This line is to remove field name display
                var strErr = jResults + '';  //make json object as string
                strErr = strErr.split(",").pop();
                alert(strErr);
            }
        });

Hope this help to anyone out there facing similar issue. By the way, I'm using Django 2.0 and Python 3.6+

Thanks MinedBP

Upvotes: 1

Related Questions