Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning form errors for AJAX request in Django

I've been finding my way around Django and jQuery. I've built a basic form in Django. On clicking submit, I'm using jQuery to make an AJAX request to the sever to post my data. This bit seems to work fine and I've managed to save the data. Django returns a ValidationError when a form is invalid. Could anyone tell me how to return this set of error messages as a response to my AJAX request so I can easily iterate through it using JS and do whatever?

I found this snippet. Looking at the JS bit (processJson) you'll see that he seems to get the error messages by extracting them from the response HTML. It seems kinda kludgy to me. Is this the best way to go about it?

My apologies for any vagueness.

Thanks in advance.

like image 751
Mridang Agarwalla Avatar asked Apr 12 '10 19:04

Mridang Agarwalla


People also ask

What triggers Ajax error?

Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the .ajaxError() method are executed at this time. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.

How can AJAX call error be resolved?

The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.

What does AJAX request return?

It receives the returned data and the value of dataType , and must return the (possibly altered) data to pass on to success . success callback option is invoked, if the request succeeds. It receives the returned data, a string containing the success code, and the jqXHR object.

How do you reset a form on Ajax success?

getElementById("form_id"). reset(); You can call this in ajax success method. so once your ajax call will be success it will reset the form.


1 Answers

This question is old, but I think the shortest answer might be using simple json in a view like this.

from django.utils import simplejson

def ajax(request):
    if request.method == 'POST':
        form = someForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse(something)
        else:
            errors = form.errors
            return HttpResponse(simplejson.dumps(errors))
    else:
        return HttpResponse(something)

now you can access the data in your jquery like Calvin described above. Jquery makes it easy to handle the data, You could do something like this:

var errors = jQuery.parseJSON(data)
    alert(errors.username)
like image 73
jarred Avatar answered Sep 20 '22 03:09

jarred