【问题标题】:When am I allowed to use the "request" object in Django?我什么时候可以在 Django 中使用“请求”对象?
【发布时间】:2019-01-21 21:47:37
【问题描述】:

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

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

有什么建议吗?

【问题讨论】:

    标签: python django


    【解决方案1】:

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

    顺便说一句,我不知道你为什么要复制 built-in form 并更改其中的内容。

    【讨论】:

    • 嗯,有道理。谢谢罗曼。那么我不能像这样简单地添加 ContextMixin 吗: class SetPasswordForm(ContextMixin, forms.Form): -- 如果是这样,后果是什么?任何可能的安全漏洞?
    • @willer2k ContextMixin(以及所有其他内置的 Django mixins,AFAIK)适用于 class-based views,而不适用于表单。所以如果你对带有表单类的 CBV 使用 mixin,它可能会导致一些无意义的行为
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2011-02-24
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 2023-03-19
    • 2018-11-24
    相关资源
    最近更新 更多