你可以write your own validator
Django 的密码验证器有一个相当小的接口。他们必须实现两种方法:
validate(self, password, user=None) 如果密码有效,则必须返回 None,或者如果密码无效,则引发带有错误消息的 ValidationError。您必须能够处理用户为 None - 如果这意味着您的验证器无法运行,则返回 None 以表示没有错误。在大多数情况下,您甚至不需要用户验证密码(更适用于我们想要防止密码重用的情况)
get_help_text() 必须提供一些帮助文本来向用户解释密码要求。
AUTH_PASSWORD_VALIDATORS 中的 OPTIONS 中的任何项目都将传递给您的验证器。所有构造函数参数都应该有一个默认值。
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
class CaptialAndSymbolValidator:
def __init__(self, number_of_capitals=1, number_of_symbols=2, symbols="[~!@#$%^&*()_+{}\":;'[]"):
self.number_of_capitals = number_of_capitals
self.number_of_symbols = number_of_symbols
self.symbols = symbols
def validate(self, password, user=None):
capitals = [char for char in password if char.isupper()]
symbols = [char for char in password if char in self.symbols]
if len(capitals) < self.number_of_capitals:
raise ValidationError(
_("This password must contain at least %(min_length)d capital letters."),
code='password_too_short',
params={'min_length': self.number_of_capitals},
)
if len(symbols) < self.number_of_symbols:
raise ValidationError(
_("This password must contain at least %(min_length)d symbols."),
code='password_too_short',
params={'min_length': self.number_of_symbols},
)
def get_help_text(self):
return _(
"Your password must contain at least %(number_of_capitals)d capital letters and %(number_of_symbols) symbols."
% {'number_of_capitals': self.number_of_capitals, 'number_of_symbols': self.number_of_symbols}
)
AUTH_PASSWORD_VALIDATORS = [
...
{
'NAME': 'path.to.your.validators.CaptialAndSymbolValidator',
'OPTIONS': {
# use this to override any of the defaults
'symbols': "@^#",
}
},
]