我试图使用“ 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 oldpassword"""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 password2def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user有什么建议么?
1 回答
慕无忌1623718
TA贡献1744条经验 获得超4个赞
request
对象可以在视图(和模板(如果需要,上下文处理器已打开))中而不是在表单中访问。您应将其传递给表单的构造函数request.user
(或self.request.user
在基于类的视图的情况下),从而在表单的__init__
方法中设置其处理方式。
顺便说一句,我不知道您为什么要复制内置表单并更改其中的内容。
添加回答
举报
0/150
提交
取消