django确认密码验证器 [英] django confirm password validator
问题描述
我有一个配置文件设置页面,用户可以在其中更改密码,如果需要,则必须确认密码。我无法将此字段设为必填字段,因为他们无需更改密码。如果密码字段不为空,是否有示例验证确认密码?然后检查它们是否相等?我找不到任何这样的示例...
I have a profile settings page where users can change their password and they have to confirm it if they do. I cannot make this a required field, since they dont HAVE to change the password. Is there an example to validate the confirm password IF the password field is not empty? And then to check if they are equal? I was not able to find any such example...
推荐答案
将以下内容添加到表单的 clean中
方法:
Add the following to your form's clean
method:
def clean(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return self.cleaned_data
编辑
上面的验证错误消息将放入 non_field_errors
中。您没有指定在每个密码字段上显示什么错误消息,但是根据上下文,我认为这是此字段必填消息。在这种情况下,请确保在定义字段时,或者您使用的是表单子类时,您的表单字段具有 required = False
实际的表单字段),您可以覆盖以下表单的 __ init __
方法:
The validation error message above will go into non_field_errors
. You didn't specify what error message is showing on each password field, but based on context, I would imagine it's a "This field is required" message. If that's the case, make sure that your form fields have required=False
when you define them, or if you're working with a form subclass (and can't edit the actual form fields) you can override the __init__
method of the form:
class MyForm(SomeOtherForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['password1'].required = False
self.fields['password2'].required = False
这篇关于django确认密码验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!