开发者

How to set cookie at user authentication in Django ?

开发者 https://www.devze.com 2023-02-09 22:41 出处:网络
Hey, can someone help me to set this cookie in django ;s Here is the code ;p class MFAuthForm(AuthenticationForm):

Hey, can someone help me to set this cookie in django ;s Here is the code ;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 us开发者_StackOverflow社区ername 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


I'll do it in the login view:

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


You should set the cookie in the response, not the request.

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

You should se t the cookie wherever you are building the response (typically your view)

0

精彩评论

暂无评论...
验证码 换一张
取 消