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

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

  1. Validation for 'unique' and 'unique_together' constraints (different version) by miracle2k 5 years, 10 months ago
  2. Automatically trim newforms text fields by miracle2k 5 years, 8 months ago
  3. Add ValidationError to a field instead of __all__ during Form.clean() by guettli 4 years, 7 months ago
  4. Scan uploaded file for viruses with clamav by uandt 4 years, 12 months ago
  5. use oldforms validators in newforms forms by garywilson 6 years, 1 month ago

Comments

Archatas (on September 12, 2008):

This is how you can blame different fields for different errors:

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)

#

Archatas (on September 12, 2008):

oh.. I forgot to return the cleaned dictionary at the end. so there should be

return cleaned

after all.

#

eopadoan (on July 8, 2009):

Archatas, instead of: self._errors['field1'] = self._errors.get('field1', [])

you should do: self._errors['field1'] = self._errors.get('field1', ErrorList())

ErrorList comes from django.forms.utils

#

(Forgotten your password?)