Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - To get form.errors as a dictionary instead of HTML code

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.

like image 344
NEB Avatar asked Dec 11 '22 12:12

NEB


2 Answers

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

like image 69
w411 3 Avatar answered Dec 22 '22 15:12

w411 3


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')
like image 20
Brandon Avatar answered Dec 22 '22 16:12

Brandon