is_valid() vs clean() django forms

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

提交回复
热议问题