Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - form Clean() and field errors

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?

like image 880
RS7 Avatar asked Apr 01 '12 21:04

RS7


People also ask

What is the form clean () method in Django?

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.

What is the difference between form and field validation in Django?

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.

What is Django’s Forms API?

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.

What are CSS classes in Django forms?

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'


2 Answers

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.

like image 85
Kiran Ruth R Avatar answered Sep 24 '22 01:09

Kiran Ruth R


  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.
like image 37
Alexander Lebedev Avatar answered Sep 22 '22 01:09

Alexander Lebedev