问题描述
我们有一个需要特定级别的密码复杂度的Django应用程序。我们目前通过客户端JavaScript执行此操作,可以轻易地被有针对性的人击败。我似乎找不到有关设置服务器端的任何具体信息密码强度验证使用django contrib内置视图。在我重新开发轮子之前,有没有正确的方法来处理这个要求?
我也去了为此定制表单。在 urls.py
中指定您的自定义表单:
(r'^ change_password / $','django.contrib.auth.views.password_change',
{'password_change_form':ValidatingPasswordChangeForm}),
继承自 PasswordChangeForm
并实施验证:
from django import form
from django.contrib import auth
class ValidatingPasswordChangeForm(auth.forms.PasswordChangeForm):
MIN_LENGTH = 8
def clean_new_password1(self):
password1 = self.cleaned_data.get('new_password1')
#至少MIN_LENGTH long
if len(password1)< self.MIN_LENGTH:
raise forms.ValidationError(新密码必须至少为%d个字符长。%self.MIN_LENGTH)
#至少一个字母和一个非字母
first_isalpha = password1 [0] .isalpha()
如果全部(c.isalpha()== first_isalpha for c in password1):
raise forms.ValidationError(新密码必须包含至少一个字母和至少一个数字或\
标点符号。)
#...您想要的任何其他验证...
返回password1
We have a Django application that requires a specific level of password complexity. We currently enforce this via client-side JavaScript which can easily be defeated by someone who is appropriately motivated.
I cannot seem to find any specific information about setting up server-side password strength validation using the django contrib built in views. Before I go about re-inventing the wheel, is there a proper way to handle this requirement?
I also went with a custom form for this. In urls.py
specify your custom form:
(r'^change_password/$', 'django.contrib.auth.views.password_change',
{'password_change_form': ValidatingPasswordChangeForm}),
Inherit from PasswordChangeForm
and implement validation:
from django import forms
from django.contrib import auth
class ValidatingPasswordChangeForm(auth.forms.PasswordChangeForm):
MIN_LENGTH = 8
def clean_new_password1(self):
password1 = self.cleaned_data.get('new_password1')
# At least MIN_LENGTH long
if len(password1) < self.MIN_LENGTH:
raise forms.ValidationError("The new password must be at least %d characters long." % self.MIN_LENGTH)
# At least one letter and one non-letter
first_isalpha = password1[0].isalpha()
if all(c.isalpha() == first_isalpha for c in password1):
raise forms.ValidationError("The new password must contain at least one letter and at least one digit or" \
" punctuation character.")
# ... any other validation you want ...
return password1
这篇关于使用django.contrib.auth.views.password_change强制实施密码强度要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!