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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
is_valid()callsclean()on the form automatically. You useis_valid()in your views, andclean()in your form classes.Your
clean()function will returnself.cleaned_datawhich if you will notice in the following view is not handled by you as the programmer.You didn’t have to do
clean_data = form.is_valid()becauseis_valid()will call clean and overwrite data in the form object to be cleaned. So everything in yourif form.is_valid()block will be clean and valid. Thenamefield in your block will be the sanitized version which is not necessarily what was inrequest.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: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.