Django form validation: get errors in JSON format

Question:

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.

Asked By: Saturnix

||

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.

Answered By: Leonardo
#from django.http import JsonResponse    

return JsonResponse({'success': False,
                      'errors': [(k, v[0]) for k, v in form.errors.items()]})
Answered By: Alex

If we want to return the errors as a valid JSON to the frontend, then the method get_json_data() seems to be a better option:

data = form.errors.get_json_data()
return JsonResponse(data, status=400, safe=False)

This way we will return a valid json:

{"amount": [{"message": "Ensure this value is greater than or equal to 100.", "code": "min_value"}]}

See: https://docs.djangoproject.com/en/4.1/ref/forms/api/#django.forms.Form.errors.get_json_data


If we use as_json() like this:

data = form.errors.as_json()
return JsonResponse(data, status=400, safe=False)

We will return a string formatted as a json:

"{"amount": [{"message": "Ensure this value is greater than or equal to 100.", "code": "min_value"}]}"
Answered By: Julian Espinel
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.