Sometimes it is very useful to add the form fields validation bypassing "clean" method of form. To do this in Django we can use "add_error" method. This method can be used directly from Django views. For example:
class TestFormView(FormView): form_class = TestForm template_name = 'test/form.html' def form_valid(self, form): less_than_one = form.cleaned_data.get('less_than_one') if less_than_one > 1: form.add_error('less_than_one', forms.ValidationError('Can not be greater than one')) return super(TestFormView, self).form_invalid(form) return super(TestFormView, self).form_valid(form)
"add_error" method was added in Django since version 1.7 (including). In earlier versions of Django (<=1.6) you can use this mixin:
from django import forms from django.forms.forms import NON_FIELD_ERRORS class AddErrorMixin(object): "Backport add_error() for django <1.7" def add_error(self, field, msg): field = field or NON_FIELD_ERRORS if field in self._errors: self._errors[field].append(msg) else: self._errors[field] = self.error_class([msg]) class ExampleForm(AddErrorMixin, forms.Form): pass
2016-04-27
