Django+表单用于重置密码



我想创建一个用于重置用户密码的表单。它应该取current_password,然后取new_passwordconfirm_new_password。我可以进行验证以检查新密码是否匹配。如何验证current_password?有没有办法将User对象传递到表单中?

Django附带了一个内置的PasswordChangeForm,您可以在视图中导入和使用它。
from django.contrib.auth.forms import PasswordChangeForm

但您甚至不必编写自己的密码重置视图。有一对视图django.contrib.with.views.password_changedjango.contrib.auth.views.password_change_done,您可以直接挂接到您的URL配置中。

找到了一个非常好的例子:http://djangosnippets.org/snippets/158/

[EDIT]

我使用了上面的链接,并做了一些更改。它们在下面:

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')

最新更新