1

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

1
  • try using dumps. Commented Mar 6, 2018 at 6:59

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I have been searching for so long. This worked wonders!! Kudos!
0

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.

3 Comments

Http 400 is not for form error. datatracker.ietf.org/doc/html/rfc7231#section-6.5.1 More over django didn't return 400 Http response by default on form error.
You are wrong. It is a Bad Request 400 HTTP Error like you can read in the RFC you posted. And yes, Django returns a 400 HTTP Error if the form is not valid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.