我正在使用the built-in auth module在Django网站中实施身份验证,包括the built-in UserCreationForm
。
我想设置密码的最小长度。但是,我找不到任何关于如何执行此操作的文档。
我是否可以将auth模块的User
模块配置为在数据库级别要求此模块?或者我应该对UserCreationForm
进行子类化(我实际上已经出于无关的原因这样做了)并添加了一个强制密码长度的额外验证器?
答案 0 :(得分:18)
我认为最简单的方法是使用Django password validation
将最小长度添加到设置文件中足够了:
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
'OPTIONS': {
'min_length': 8,
}
},
]
还有其他验证工具,例如NumericPasswordValidator
和CommonPasswordValidator
答案 1 :(得分:8)
特别是如果你已经使用了一个子类UserCreationForm
,我会说你绝对应该只是添加验证。您应该能够覆盖表单上的clean_password
方法:
def clean_password(self):
password = self.cleaned_data.get('password1')
if len(password) < 8:
raise ValidationError('Password too short')
return super(MyUserCreationForm, self).clean_password1()
答案 2 :(得分:5)
对用户创建表单进行子类化听起来是一种很好的方法。您不能在数据库级别强制执行它,因为Django只存储密码的哈希值。
答案 3 :(得分:1)
/django/contrib/auth/password_validation.py包含类MinimumLengthValidator,默认密码最小长度为:
class MinimumLengthValidator(object):
"""
Validate whether the password is of a minimum length.
"""
def __init__(self, min_length=8):
self.min_length = min_length
def validate(self, password, user=None):
if len(password) < self.min_length:
raise ValidationError(
ungettext(
"This password is too short. It must contain at least %(min_length)d character.",
"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 ungettext(
"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}
答案 4 :(得分:0)
有关答案的一些信息,
django.contrib.auth.password_validation.MinimumLengthValidator
是django 1.9+的新版本,不适用于较旧的版本,
因此您可以使用自己的自定义验证器,
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext
def validate(min_length, password):
special_characters = "[~\!@#\$%\^&\*\(\)_\+{}\":;'\[\]]"
if len(password) < 8:
raise ValidationError(ugettext('Password length must be greater than 8 character.'))
if not any(char.isdigit() for char in password):
raise ValidationError(ugettext('Password must contain at least %(min_length)d digit.') % {'min_length': min_length})
if not any(char.isalpha() for char in password):
raise ValidationError(ugettext('Password must contain at least %(min_length)d letter.') % {'min_length': min_length})
if not any(char in special_characters for char in password):
raise ValidationError(ugettext('Password must contain at least %(min_length)d special character.') % {'min_length': min_length})