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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…