何时可以在Django中使用“请求”对象?

时间:2018-08-15 00:53:41

标签: python django

我试图使用“ request.user”传递当前用户的实例,但是当我尝试在需要的地方访问“ request”对象时,出现错误:

NameError: name 'request' is not defined

当我尝试使用self.request.user时,我遇到类似的错误(PasswordChangeForm继承了SetPasswordForm):

AttributeError: 'PasswordChangeForm' object has no attribute 'request'

这是我使用的表单类(def __init__中的请求用法):

class SetPasswordForm(forms.Form):
"""
A form that lets a user change set their password without entering the old
password
"""
error_messages = {
    'password_mismatch': _("The two password fields didn't match."),
}
new_password1 = forms.CharField(
    label=_("New password"),
    widget=forms.PasswordInput,
    strip=False,
    help_text=password_validation.password_validators_help_text_html(),
)
new_password2 = forms.CharField(
    label=_("New password confirmation"),
    strip=False,
    widget=forms.PasswordInput,
)

def __init__(self, *args, **kwargs):
    self.user = request.user
    super().__init__(*args, **kwargs)

def clean_new_password2(self):
    password1 = self.cleaned_data.get('new_password1')
    password2 = self.cleaned_data.get('new_password2')
    if password1 and password2:
        if password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
    password_validation.validate_password(password2, self.user)
    return password2

def save(self, commit=True):
    password = self.cleaned_data["new_password1"]
    self.user.set_password(password)
    if commit:
        self.user.save()
    return self.user

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

request对象可以在视图(和模板,如果需要上下文处理器已打开)中而不是在表单中访问。您应该将request.user(如果是基于类的视图,则为self.request.user)传递给表单的构造函数,从而在表单的__init__方法中设置其处理方式。

顺便说一句,我不知道您为什么要复制built-in form并在其中进行更改。