Is there a way to get the form errors generated during the django form validation in a dictionary (key as the 'field_name' and value as 'the list of errors relevant to it'), instead of the default HTML code it generates (ul & li combination). I'm not using the generated HTML code, and I'm just bothered about the field name and the errors.
There's not built-in method for return errors as dict
, but you can use json.
form = MyForm(data)
print(form.errors.as_json())
doc for errors.as_json
Sure. I use this class often when doing forms that are Ajaxed and I need to return JSON instead. Tweak/improve as necessary. In some cases, you might want to return HTML encoded in the JSON, so I pass in the stripping of HTML tags as an option.
from django import forms
from django.template.defaultfilters import striptags
class AjaxBaseForm(forms.BaseForm):
def errors_as_json(self, strip_tags=False):
error_summary = {}
errors = {}
for error in self.errors.iteritems():
errors.update({error[0]: unicode(striptags(error[1])
if strip_tags else error[1])})
error_summary.update({'errors': errors})
return error_summary
Usage:
# forms.py
class MyForm(AjaxBaseForm, forms.Form): # you can also extend ModelForm
...
# views.py
def my_view(request):
form = MyForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
...
else:
response = form.errors_as_json(strip_tags=True)
return HttpResponse(json.dumps(response, ensure_ascii=False),
content_type='application/json')
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