3

I have a file forms.py where I define all my forms. I need to do a password validation on one of my form fields.

In my forms.py

class ChangePasswordForm(forms.Form):
    old_password = forms.CharField(widget=forms.PasswordInput)
    new_password= forms.CharField(widget=forms.PasswordInput)
    new_password_again= forms.CharField(widget=forms.PasswordInput)

    def clean_old_password(self):
        data = self.cleaned_data['old_password']
        if data != currently_logged_in_user.password:
            raise forms.ValidationError("Password Incorrect")

        return data

I need to get access to the currently logged in user so I can use currently_logged_in_user.password for the validation but am currently working in forms.py not views.py so I dont know how to do so? Help please

flexxxit
  • 2,440
  • 5
  • 42
  • 69

1 Answers1

2

You need to pass user from views to your form. You can do this way:

views.py

my_form = ChangePasswordForm(user=request.user, data=request.POST)
...

forms.py

class ChangePasswordForm(forms.Form):
    ...

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(ChangePasswordForm, self).__init__(*args, **kwargs)

    def clean_old_password(self):
        old_password = self.cleaned_data['old_password']
        if not self.user.check_password(old_password)
            raise forms.ValidationError("Password Incorrect")
        return old_password
supervacuo
  • 9,072
  • 2
  • 44
  • 61
San4ez
  • 8,091
  • 4
  • 41
  • 62
  • data != self.user.password always evaluates to a True value so I used auth=authenticate(username=self.user.username,password=data) instead. It works Thanks – flexxxit Aug 23 '12 at 15:19
  • Yep, `self.user.password` would be the hashed value including the salt. [From the docs](https://docs.djangoproject.com/en/1.4/topics/auth/#manually-managing-a-user-s-password), "If you'd like to manually authenticate a user by comparing a plain-text password to the hashed password in the database, use the convenience function `django.contrib.auth.hashers.check_password()`". – supervacuo Aug 23 '12 at 15:30