Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is_valid() vs clean() django forms

In the process of finding a way to validate my django forms, I came across two methods is_valid() and clean() in the django docs. Can anyone enlighten me the how they are different/same? What are the pros and cons of either?

Thanks.

like image 966
stackover Avatar asked Feb 22 '11 20:02

stackover


2 Answers

is_valid() calls clean() on the form automatically. You use is_valid() in your views, and clean() in your form classes.

Your clean() function will return self.cleaned_data which if you will notice in the following view is not handled by you as the programmer.

form = myforms.SettingsForm(request.POST) if form.is_valid():    name = form.cleaned_data['name']    #do stuff 

You didn't have to do clean_data = form.is_valid() because is_valid() will call clean and overwrite data in the form object to be cleaned. So everything in your if form.is_valid() block will be clean and valid. The name field in your block will be the sanitized version which is not necessarily what was in request.POST.

Update You can also display error messages with this. In clean() if the form data isn't valid you can set an error message on a field like this:

self._errors['email'] = [u'Email is already in use'] 

Now is_valid() will return False, so in the else block you can redisplay the page with your overwritten form object and it will display the error message if your template uses the error string.

like image 71
jonescb Avatar answered Oct 01 '22 22:10

jonescb


Just wanted to add that the best way now to add an error to a form you're manually validating in is_valid() is to use Form.add_error(field, error) to conform with Django's ErrorDict object.

Doing

self._errors['field'] = ['error message'] 

will come out funky when rendering {{form.errors}}, like:

fielderror messsage 

instead of the expected

field     -error message 

so instead do:

self.add_error('email', 'Email is already in use') 

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

like image 40
InfiniteZoom Avatar answered Oct 01 '22 22:10

InfiniteZoom