我试图使用“ 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
有什么建议吗?
答案 0 :(得分:1)
request
对象可以在视图(和模板,如果需要上下文处理器已打开)中而不是在表单中访问。您应该将request.user
(如果是基于类的视图,则为self.request.user
)传递给表单的构造函数,从而在表单的__init__
方法中设置其处理方式。
顺便说一句,我不知道您为什么要复制built-in form并在其中进行更改。