I wanted to create a form for resetting the user's password. It should take the current_password
, and then the new_password
and confirm_new_password
. I'm able to do the validation to check the new passwords are matching. How would I be able to validate the current_password
? Is there a way to pass in the User
object into the form?
问问题
3220 次
2 回答
6
Django 带有一个内置PasswordChangeForm
功能,您可以在视图中导入和使用它。
from django.contrib.auth.forms import PasswordChangeForm
但是您甚至不必编写自己的密码重置视图。有一对视图django.contrib.with.views.password_change
和django.contrib.auth.views.password_change_done
,您可以直接挂接到您的 URL 配置中。
于 2012-07-27T00:42:21.567 回答
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')
于 2012-07-27T00:32:06.167 回答