is_valid() vs clean() django forms

前端 未结 2 1232
庸人自扰
庸人自扰 2020-12-07 21:02

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 di

2条回答
  •  感情败类
    2020-12-07 21:21

    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.

提交回复
热议问题