更新:子类化而不是复制/粘贴可能是更好的解决方案。看古斯塔沃的回答 https://stackoverflow.com/a/54442904/9638991.
See 除了 django auth 密码验证器之外,如何使用自定义密码验证器? https://stackoverflow.com/questions/43915518/how-to-use-custom-password-validators-beside-the-django-auth-password-validators类似的说明。
我一直在寻找同样的事情,但我认为没有任何方法可以从表单级别更改密码验证器上的错误消息。您可能最终不得不编写自己的自定义验证器,然后将其包含在您的AUTH_PASSWORD_VALIDATORS
in settings.py
(这就是我所做的)。我是这样做的:
1.转到 django 的内置密码验证器并复制 MaximumLengthValidator 代码。这是链接:https://docs.djangoproject.com/en/2.0/_modules/django/contrib/auth/password_validation/#MinimumLengthValidator https://docs.djangoproject.com/en/2.0/_modules/django/contrib/auth/password_validation/#MinimumLengthValidator
2.在您选择的应用程序(我选择了我的基本应用程序)中创建一个 python 文件,并为其指定您选择的名称(我的是custom_validators.py
)
我的看起来像这样:
from django.utils.translation import ngettext # https://docs.python.org/2/library/gettext.html#gettext.ngettext
from django.core.exceptions import ValidationError
# https://docs.djangoproject.com/en/2.0/_modules/django/contrib/auth/password_validation/#MinimumLengthValidator
class MyCustomMinimumLengthValidator(object):
def __init__(self, min_length=8): # put default min_length here
self.min_length = min_length
def validate(self, password, user=None):
if len(password) < self.min_length:
raise ValidationError(
ngettext(
# silly, I know, but if your min length is one, put your message here
"This password is too short. It must contain at least %(min_length)d character.",
# if it's more than one (which it probably is) put your message here
"This password is too short. It must contain at least %(min_length)d characters.",
self.min_length
),
code='password_too_short',
params={'min_length': self.min_length},
)
def get_help_text(self):
return ngettext(
# you can also change the help text to whatever you want for use in the templates (password.help_text)
"Your password must contain at least %(min_length)d character.",
"Your password must contain at least %(min_length)d characters.",
self.min_length
) % {'min_length': self.min_length}
3. In settings.py
,注释掉您的以下行AUTH_PASSWORD_VALIDATORS
:
# {
# 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
# },
并添加以下行:
{
'NAME': 'base.custom_validators.MyCustomMinimumLengthValidator',
# app_name.file_name.validator_name
},
现在,每当你跑步时validate()
or form.is_valid()
(它也运行validate()
)您的密码将通过新的自定义密码验证器而不是 django 的默认密码验证器。这可能需要一些调整,但您可能可以对 django 的所有默认验证器执行此操作。
希望有帮助!