13

I'm trying to set field errors in a form clean() and I'm currently doing:

self._errors['address'] = self._errors.get('address', ErrorList())
self._errors['address'].append(_(u'Please specify an address.'))

Is there a better and if possible shorter method for doing this?

RS7
  • 2,341
  • 8
  • 34
  • 57

3 Answers3

14

New in Django 1.7 is Form.add_error( field, message ).

https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.add_error

guettli
  • 25,042
  • 81
  • 346
  • 663
ManicDee
  • 732
  • 6
  • 16
8

Maybe this will help you . Its generally preferred you override clean and inside the function you could do the following

If you want to raise form specific errors you could do .

self._errors["field"] = ErrorList([u"Error"])

this is make sure you get the error class

if you have an non field error you could simple raise a validation error like so

raise forms.ValidationError(_("Error"))

Hope this helps.

Kiran Ruth R
  • 902
  • 1
  • 11
  • 28
6
  1. Standard way is raise ValidationError(message).
  2. Move field-specific validation to clean_<fieldname>() methods, clean_address in your case. ValidationError raised in such method will attach error message to specific field. One raised from clean() will be attributed to model in general.
Alexander Lebedev
  • 5,968
  • 1
  • 20
  • 30
  • 1
    I'm currently using `clean()` for validating certain things related to multiple fields -- I'm quite new to Django and Python in general and I was wondering if there was better/shorter way for checking/creating/appending field specific errors. – RS7 Apr 01 '12 at 22:00
  • Added item #3, perhaps it describes what you need. Taken from django's internal implementation of `clean_fields` – Alexander Lebedev Apr 01 '12 at 22:11
  • Can you expand on your suggestion #3? It doesn't work for me. I can see that the [`ValidationError` class](https://code.djangoproject.com/browser/django/trunk/django/core/exceptions.py#L41) accepts a dictionary of errors like that, but [`Forms._clean_form`](https://code.djangoproject.com/browser/django/trunk/django/forms/forms.py#L297) doesn't actually make use of it. – Gareth Rees Apr 02 '12 at 11:21
  • @AlexLebedev - I haven't tested your third suggestion but according to the docs that would be incorrect, no? When setting field specific errors, one should assign messages to `self._errors`. – RS7 Apr 02 '12 at 15:48
  • You're right, I confused form and model validation. #3 will only work for models. – Alexander Lebedev Apr 02 '12 at 17:31