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.
Wow, it’s been a year since I’ve seen this thread. Well, with the advent of Django 1.3 and the magical, undocumented class-based views, it’s become more easy to extent Django’s view related functionality. My project which makes heavy use of Django’s class-based generic CRUS views need AJAX and JSON functionality. I’ve added an example of how I’ve modified Django’s update view to support AJAX and return AJAX responses in the JSON format. Have a look:
The response JSON contains three fields —
message(which is a human readable message),data(which is this case would be the list of form errors) andsuccess(which is eithertrueorfalse, indicating whether the request was successful or not respectively.). This is very easy to handle in jQuery client-side. A sample response looks like:This is just an example of how I serialized the form errors to JSON and implemented it in a class-based generic view but can be cannibalized to work with regular style views as well.