我正在使用Django 1.10.6并在注册表单上工作。在forms.py
我想使用密码表单字段的min_length
参数来帮助防止不必要的服务器请求,因为Django将该属性添加到CSS,大多数浏览器会在允许表单之前检查它提交。
然而,在某些情况下,当我使用form field validation和AUTH_PASSWORD_VALIDATORS
时,Django似乎不喜欢。当我在注册页面上打开检查器并删除密码输入的min_length
属性的CSS(从而阻止我的浏览器提示输入更多字符)并提交少于8个字符的请求时,表单字段验证失败,Django删除/清空(很抱歉,不确定正确的术语)清理后的数据,因此密码为None
,这会导致AUTH_PASSWORD_VALIDATORS
的其余部分抛出错误。这是导致object of type 'NoneType' has no len()
这是我在forms.py
上的注册课程class RegisterForm(forms.Form):
username = forms.CharField(label="Username", max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'}))
email = forms.CharField(label="Email", max_length=254,
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'email'}))
# when I remove the min_length here it works,
# however I would like to have the benefit of the input's min_length being checked by the browser first
password = forms.CharField(label="Password", min_length=8,
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'password', 'type' : 'password'}))
repassword = forms.CharField(label="Re-Enter Password",
widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'repassword', 'type' : 'password'}))
def clean(self):
cleaned_data = super(RegisterForm, self).clean()
password1 = cleaned_data.get('password')
password2 = cleaned_data.get('repassword')
#validate that the two passwords match each other
if password1 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
# when the following 2 lines are uncommented
# and I remove the min_length validator via inspector
# and enter a password shorter than 8, password1 is None
# print(password1)
# import pdb;pdb.set_trace()
validators = passwordValidation.get_default_password_validators()
passwordValidation.validate_password(password1,User,validators)
以下是settings.py
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
# I've tried this commented and uncommented, same results either way
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
'OPTIONS': { 'min_length' : 8 }
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
有没有办法我仍然可以使用表单字段提供的客户端min_length验证以及使用validate_password
方法?
修改 - 忘记添加我可以通过单独调用django.contrib.auth.password_validation中找到的每个类来绕过这个,但似乎这是有标准方法的情况之一它,但我不知道。例如......
from django.contrib.auth.password_validation import CommonPasswordValidator
...
if CommonPasswordValidator().validate(password1):
raise forms.ValidationError("Please choose another password")