gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:35:55 25 4
gpt4 key购买 nike

这是我的代码:

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 方法,然后从您的 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 - 如何在 Django 中设置或获取 cookie 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5113660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com