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.

5
  • 2
    Related: stackoverflow.com/questions/986406/… Commented May 18, 2014 at 1:54
  • thanks! I feel stupid for having not noticed that myself. Reading it now. Commented May 18, 2014 at 1:55
  • yes, form.errors.items() solved the problem - still have to localize the message thought. Commented May 18, 2014 at 2:01
  • Docs should help with it. Commented May 18, 2014 at 2:05
  • Does this answer your question? Returning pure Django form errors in JSON Commented Nov 29, 2021 at 18:13

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

5
#from django.http import JsonResponse    

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

2 Comments

This variation code works for me: return JsonResponse({'error': [{"field":k, "message": v[0]} for k, v in form.errors.items()] })
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()]
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\"}]}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.