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
You need to pass user from views to your form. You can do this way:
my_form = ChangePasswordForm(user=request.user, data=request.POST) ...
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