如何在django中设置或获取cookie值

时间:2011-02-25 04:36:13

标签: django cookies

这是我的代码:

from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django import http
from django.http import HttpResponse 

def main(request, template_name='index.html'):
    HttpResponse.set_cookie('logged_in_status', 'zjm1126')
    context ={
              'a':a,
              'cookie':HttpResponse.get_cookie('logged_in_status'),
    }

    return render_to_response(template_name, context)
    #return http.HttpResponsePermanentRedirect(template_name)

它引发了这个例外:

unbound method set_cookie() must be called with HttpResponse instance as first argument (got str instance instead)

我该怎么办?

1 个答案:

答案 0 :(得分:101)

你不能只是开始在HttpResponse类上调用方法,你必须实例化它,例如response = HttpResponse("Hello World"),调用Cookie方法,然后从您的视图中返回。

response = render_to_response(template_name, context)

response.set_cookie('logged_in_status', 'never_use_this_ever') 
return response
# remember my other answer: 
# it's a terrrible idea to set logged in status on a cookie.

获取cookie:

request.COOKIES.get('logged_in_status') 
# remember, this is a terrible idea.