【问题标题】:How to set cookie at user authentication in Django ?如何在 Django 中的用户身份验证中设置 cookie?
【发布时间】:2013-11-28 08:52:58
【问题描述】:

嘿,谁能帮我在 django 中设置这个 cookie ;s 这是代码 ;p

class MFAuthForm(AuthenticationForm):
def clean(self):
    username = self.cleaned_data.get('username')
    password = self.cleaned_data.get('password')

    if username and password:
        self.user_cache = authenticate(username=username, password=password)
    self.request.set_cookie("mfusername", username)
        if self.user_cache is None:
            raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
        elif not self.user_cache.is_active:
            raise forms.ValidationError(_("This account is not yet active."))
        elif self.user_cache.penalty > 1:
            raise forms.ValidationError(_("For unfair treatment of the conditions of the site, MacroFactor has removed your account. To use the services of MacroFactor you need to register again. In subsequent registration please stick to the established rules. "))

    # TODO: determine whether this should move to its own method.
    if self.request:
        if not self.request.session.test_cookie_worked():
            raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))

    return self.cleaned_data

【问题讨论】:

标签: django cookies request


【解决方案1】:

我会在登录视图中做:

username = ''

if request.method == 'POST':
    if form.is_valid():
        username = form.cleaned_data['username']

response = render_to_response(...)
# if you are using redirect, 
# response = redirect(...)

if username:
    response.set_cookie("mfusername", username)

return response

【讨论】:

    【解决方案2】:

    您应该在响应中设置 cookie,而不是在请求中。

    http://docs.djangoproject.com/en/1.2/ref/request-response/#django.http.HttpResponse.set_cookie

    您应该在构建响应的任何位置(通常是您的视图)设置 cookie

    【讨论】:

    • 如果可以的话,我会做的,伙计,但我寻求帮助,因为我在这两天骑自行车..
    猜你喜欢
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 2020-10-20
    • 2014-05-04
    • 2010-12-23
    相关资源
    最近更新 更多