is_valid() vs clean() django forms

前端 未结 2 1231
庸人自扰
庸人自扰 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.

    0 讨论(0)
  • 2020-12-07 21:22

    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

    0 讨论(0)
提交回复
热议问题