Accessing request.user outside views.py

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

Answers


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

Need Your Help

How to use Paypal API with payflow pro

paypal

I have a site which runs smoothly with PayPal and express checkout. NOw my client wants a refrence transaction (billed directly from customer when he ordered via cellphone etc without involving h...

Find the highest prime number in a given range

php arrays primes

I need to find the highest prime number in a given range.