Show form errors (non field errors)

Posted: February 5th, 2010 | Author: Davo | Filed under: Django | Tags: , , , | No Comments »

In the current Django version it is possible to implement form validation by overriding the clean() function.
For instance a ContactForm:

class ContactForm(forms.Form):
    # ... fields...
   field1 = forms.IntegerField()

   def clean(self)
       cleaned_data = self.cleaned_data
       f = cleaned_data.get('field1')
       if f > 10:
          raise forms.ValidationError("Did you just enter more than 10?")
       return cleaned_data # Never forget this otherwise you will end up with empty request.POST in the views.py.

In order to show that “Did you just enter more than 10″ error in the template:

<!-- assuming that you have form as ContactForm. -->
{{ form.non_field_errors }}