在views.py之外访问request.user

时间:2012-08-23 13:48:59

标签: django forms validation

我有一个文件forms.py,我在其中定义了所有表单。我需要在我的一个表单字段上进行密码验证。

在我的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

我需要访问当前登录的用户,以便我可以使用currently_logged_in_user.password进行验证,但我目前正在使用forms.py而不是views.py,所以我不知道该怎么做?请帮忙

1 个答案:

答案 0 :(得分:2)

您需要将用户从视图传递到表单。你可以这样做:

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