我想创建一个用于重置用户密码的表单。它应该是current_password
,然后是new_password
和confirm_new_password
。我能够进行验证以检查新密码是否匹配。我如何验证current_password
?有没有办法将User
对象传入表单?
答案 0 :(得分:6)
Django附带内置PasswordChangeForm
,您可以在视图中导入和使用。
from django.contrib.auth.forms import PasswordChangeForm
但您甚至不必编写自己的密码重置视图。有一对视图django.contrib.with.views.password_change
和django.contrib.auth.views.password_change_done
,您可以直接连接到您的网址配置。
答案 1 :(得分:0)
找到了一个很好的例子:http://djangosnippets.org/snippets/158/
<强> [编辑] 强>
我使用了上面的链接并进行了一些更改。他们在下面:
class PasswordForm(forms.Form):
password = forms.CharField(widget=forms.PasswordInput, required=False)
confirm_password = forms.CharField(widget=forms.PasswordInput, required=False)
current_password = forms.CharField(widget=forms.PasswordInput, required=False)
def __init__(self, user, *args, **kwargs):
self.user = user
super(PasswordForm, self).__init__(*args, **kwargs)
def clean_current_password(self):
# If the user entered the current password, make sure it's right
if self.cleaned_data['current_password'] and not self.user.check_password(self.cleaned_data['current_password']):
raise ValidationError('This is not your current password. Please try again.')
# If the user entered the current password, make sure they entered the new passwords as well
if self.cleaned_data['current_password'] and not (self.cleaned_data['password'] or self.cleaned_data['confirm_password']):
raise ValidationError('Please enter a new password and a confirmation to update.')
return self.cleaned_data['current_password']
def clean_confirm_password(self):
# Make sure the new password and confirmation match
password1 = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('confirm_password')
if password1 != password2:
raise forms.ValidationError("Your passwords didn't match. Please try again.")
return self.cleaned_data.get('confirm_password')