Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django form validation: get errors in JSON format

I have this very simple Django form

from django import forms

class RegistrationForm(forms.Form):
    Username = forms.CharField()
    Password = forms.CharField()

I manage this manually and don't use the template engine. Rather, I send data with ajax POST and expect to receive back validation errors. While I was working with other frameworks, I used to receive validation errors in JSON format in key-value pairs (the key being the name of the field with the error and the value being the error message).

{
  Username: "This field is required.",
  Password: "This field is required.",
}

I'm trying to achieve the same result in Django, but I don't understand how can I access the raw error messages (relative to a single field) and localize them.

form.errors give access to HTML code (as explained here: displaying django form validation errors for ModelForms). I don't need that. I'd prefer something like form.Username.validationError: does such a thing exists?

If yes, additionally I'd also like to know if the validation error message is automatically translated into the user language and, if not, the best way to do that.

like image 431
Saturnix Avatar asked May 18 '14 01:05

Saturnix


2 Answers

Django let you send the forms errors as Json. You only need to use the errors in the following form form.errors.as_json().

A great addition to the library I must say.

Updated: updated link thanks donrondadon comment on this thread.

like image 143
Leonardo Avatar answered Sep 29 '22 01:09

Leonardo


#from django.http import JsonResponse    

return JsonResponse({'success': False,
                      'errors': [(k, v[0]) for k, v in form.errors.items()]})
like image 40
Alex Avatar answered Sep 29 '22 00:09

Alex