我试图使用“ 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
有什么建议么?
慕无忌1623718
相关分类