gpt4 book ai didi

python - Django 密码验证器 : If any three of the validations pass user can go ahead

转载 作者:行者123 更新时间:2023-12-04 10:07:52 26 4
gpt4 key购买 nike

我正在研究如何设置必须通过的验证次数以允许用户设置密码。

例如,我们有这 5 个验证器:

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
{ 'NAME': 'registration.validators.CustomPasswordValidator',}
]

我们希望用户密码是否通过了他们的 3 个要求中的任何一个。用户可以创建一个帐户。知道我们如何在 Django 中做到这一点吗?

最佳答案

您可以将其他验证器包装在自定义验证器中:

# pw.py
class WrapPasswordValidator:
def __init__(self, validators=None, num=3):
self.validators = validators or []
self.num = num

def validate(self, password, user=None):
errors, passed = [], 0
for v in self.validators:
try:
v.validate(password, user)
except ValidationError as e:
errors.append(e)
else:
passed += 1
if passed < self.num:
errors.insert(0, ValidationError("Fix at least {} of the following errors:".format(
self.num-passed)))
raise ValidationError(errors)

def get_help_text(self):
text = ngettext(
"Password must comply with at least %(num)d rule of:",
"Password must comply with at least %(num)d rules of:",
self.num
) % {'num': self.num}
for v in self.validators:
text += '<br>' + v.get_help_text()
return mark_safe(text)

并在您的设置中使用它:
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "pw.WrapPasswordValidator",
"OPTIONS": {
"num": 3,
"validators": [
UserAttributeSimilarityValidator(),
MinimumLengthValidator(),
CommonPasswordValidator(),
NumericPasswordValidator(),
]
}
},
]

关于python - Django 密码验证器 : If any three of the validations pass user can go ahead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61480807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com