3

我有一个文件 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.pyviews.py知道该怎么做?请帮忙

4

1 回答 1

2

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

视图.py

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

表格.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
于 2012-08-23T14:08:34.010 回答