我们有一个 Django 应用程序需要特定级别的密码复杂性。我们目前通过客户端 JavaScript 执行此操作,这很容易被有适当动机的人击败。
我似乎找不到任何关于使用内置 View 的 django contrib 设置服务器端密码强度验证的具体信息。在我开始重新发明轮子之前,是否有适当的方法来处理这个要求?
最佳答案
我还为此使用了自定义表单。在 urls.py
中指定您的自定义表单:
(r'^change_password/$', 'django.contrib.auth.views.password_change',
{'password_change_form': ValidatingPasswordChangeForm}),
继承PasswordChangeForm
并实现验证:
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 - 使用 django.contrib.auth.views.password_change 强制执行密码强度要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5226329/