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?
This is the form's clean () method , do not confuse it with clean () method on a field that we did above. Django docs says It’s important to keep the field and form difference clear when working out where to validate things. Fields are single data points, forms are a collection of fields.
Django docs says It’s important to keep the field and form difference clear when working out where to validate things. Fields are single data points, forms are a collection of fields. This method is used in cleaning and validating fields that depend on each other.
This document covers the gritty details of Django’s forms API. You should read the introduction to working with formsfirst. Bound and unbound forms¶ A Forminstance is either boundto a set of data, or unbound. If it’s boundto a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML.
When you use Django’s rendering shortcuts, CSS classes are used to indicate required form fields or fields that contain errors. If you’re manually rendering a form, you can access these CSS classes using the css_classesmethod: >>> f=ContactForm(data={'message':''})>>> f['message'].css_classes()'required'
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.
raise ValidationError(message)
.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With