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.
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.
#from django.http import JsonResponse
return JsonResponse({'success': False,
'errors': [(k, v[0]) for k, v in form.errors.items()]})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With