Login

newforms: Add field-specific error in form.clean()

Author:
miracle2k
Posted:
July 23, 2007
Language:
Python
Version:
.96
Tags:
newforms forms validation clean
Score:
4 (after 4 ratings)

This is a bit of a hack, but as far as I can see currently the only way to specify a validation error that is specific to a field in form.clean().

I am aware of clean_<fieldname>, but those are difficult to use when the validation process for a field involves other fields as well, because the necessary data might at that point not be yet available in form.cleaned_data.

1
2
3
4
5
6
7
8
def clean(self):	
    try:
        # do validation here
    except ValidationError, e:
        if blame_field:
	    self._errors[blame_field] = e.messages
        else:
            raise e

More like this

Comments

Archatas (on September 12, 2008):
<p>This is how you can blame different fields for different errors:</p> <pre>def clean(self): cleaned = self.cleaned_data errors = False # ... if there_are_errors_for_field1: self._errors['field1'] = self._errors.get('field1', []) self._errors['field1'].append(_("Field 1 is invalid")) errors = True # ... if there_are_errors_for_field2: self._errors['field2'] = self._errors.get('field2', []) self._errors['field2'].append(_("Field 2 is invalid")) errors = True # ... non_field_errors = [] if there_are_other_errors: non_field_errors.append(_("Non field error")) errors = True if errors: raise form.ValidationError(non_field_errors) </pre>

#

Archatas (on September 12, 2008):
<p>oh.. I forgot to return the cleaned dictionary at the end. so there should be</p> <pre>return cleaned </pre> <p>after all.</p>

#

eopadoan (on July 8, 2009):
<p>Archatas, instead of: self._errors['field1'] = self._errors.get('field1', [])</p> <p>you should do: self._errors['field1'] = self._errors.get('field1', ErrorList())</p> <p>ErrorList comes from django.forms.utils</p>

#

Please login first before commenting.