【问题标题】:Charfield must match with another Charfield Django form validationCharfield 必须与另一个 Charfield Django 表单验证匹配
【发布时间】:2016-06-21 15:09:51
【问题描述】:

您好,我无法找到有关 charfield 必须与另一个 charfield 匹配的验证的文档

例如,我想要验证 new_password 必须与 confirm_new_password 匹配:

class ChangePassword(forms.Form):
    new_password = forms.CharField(label='New Password', max_length=100, error_messages={'required': 'New password is required'}, widget=forms.PasswordInput())
    confirm_new_password = forms.CharField(label='Confirm New Password', max_length=100, error_messages={'required': 'Confirm New password is required'}, widget=forms.PasswordInput())

https://docs.djangoproject.com/en/1.9/ref/forms/fields/#charfield

好像主要是required, max_length, min_length

【问题讨论】:

标签: django django-forms


【解决方案1】:

要执行自定义表单验证,您需要像这样覆盖 clean() 函数:

class ChangePassword(forms.Form):
    new_password = forms.CharField(label='New Password', max_length=100, error_messages={'required': 'New password is required'}, widget=forms.PasswordInput())
    confirm_new_password = forms.CharField(label='Confirm New Password', max_length=100, error_messages={'required': 'Confirm New password is required'}, widget=forms.PasswordInput())

    def clean(self):
        password = self.cleaned_data['new_password']
        confirm_password = self.cleaned_data['confirm_new_password']
        if password != confirm_password:
            raise forms.ValidationError('Your passwords do not match!')

【讨论】:

  • 如果用户没有为其中一个字段输入值,此示例将给出KeyError。 Sayse 链接的文档显示了如何正确执行此操作。
  • 正确,感谢您的回复。这只是为了解决突出显示的主要问题的示例。
猜你喜欢
  • 2015-03-24
  • 2015-11-20
  • 2014-06-18
  • 1970-01-01
  • 1970-01-01
  • 2019-05-26
  • 2011-12-24
  • 2016-08-10
  • 2017-06-24
相关资源
最近更新 更多