嘿,有人可以帮我在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
答案 0 :(得分: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
答案 1 :(得分:0)
您应该在响应中设置cookie,而不是请求。
http://docs.djangoproject.com/en/1.2/ref/request-response/#django.http.HttpResponse.set_cookie
您应该在构建响应的任何地方(通常是您的视图)中找到cookie