如何在django中设置或获取cookie值 [英] How to set or get a cookie value in django

查看:1245
本文介绍了如何在django中设置或获取cookie值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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)

我能做什么?

推荐答案

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

You can't just start calling methods on the HttpResponse class, you have to instantiate it e.g. response = HttpResponse("Hello World"), call the cookie method, and then return it from your view.

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.

这篇关于如何在django中设置或获取cookie值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆