Django + password reset

I wanted to create a user password reset form. He must take current_password, and then new_passwordand confirm_new_password. I can perform a check to verify that the new passwords match. How can i check current_password? Is there a way to pass an object Userto a form?

+5
source share
2 answers

Django comes with a built-in PasswordChangeFormthat you can import and use in your presentation.

from django.contrib.auth.forms import PasswordChangeForm

But you don’t even need to write your own reset password. There are a couple of views django.contrib.with.views.password_changeand ones django.contrib.auth.views.password_change_donethat you can connect directly to your URL configuration.

+6
source

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

All Articles