7

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.

Community
  • 1
  • 1
Saturnix
  • 10,130
  • 17
  • 64
  • 120
  • 2
    Related: http://stackoverflow.com/questions/986406/returning-pure-django-form-errors-in-json – alecxe May 18 '14 at 01:54
  • thanks! I feel stupid for having not noticed that myself. Reading it now. – Saturnix May 18 '14 at 01:55
  • yes, form.errors.items() solved the problem - still have to localize the message thought. – Saturnix May 18 '14 at 02:01
  • [Docs](https://docs.djangoproject.com/en/dev/topics/i18n/translation/) should help with it. – alecxe May 18 '14 at 02:05
  • Does this answer your question? [Returning pure Django form errors in JSON](https://stackoverflow.com/questions/986406/returning-pure-django-form-errors-in-json) – ggorlen Nov 29 '21 at 18:13

3 Answers3

11

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.

Leonardo
  • 2,484
  • 2
  • 25
  • 37
  • 1
    [Working link](https://docs.djangoproject.com/en/3.0/ref/forms/api/#django.forms.Form.errors.as_json) – ron_g Feb 24 '20 at 11:09
5
#from django.http import JsonResponse    

return JsonResponse({'success': False,
                      'errors': [(k, v[0]) for k, v in form.errors.items()]})
Alex
  • 5,759
  • 1
  • 32
  • 47
  • This variation code works for me: `return JsonResponse({'error': [{"field":k, "message": v[0]} for k, v in form.errors.items()] })` – Jorge Gonzalez Apr 05 '18 at 11:36
  • i think since Django puts errors in a list, this would be better : `[{k: [b]for b in v} for k, v in frm.errors.items()]` – Ebrahim Karimi Apr 03 '19 at 08:38
0

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\"}]}"
Julian Espinel
  • 2,586
  • 5
  • 26
  • 20