【问题标题】:cookies not working in djangocookie 在 Django 中不起作用
【发布时间】:2016-11-18 17:12:01
【问题描述】:

我必须设置 cookie 以在我的项目中保存购物车详细信息,但是当我使用函数测试 cookie 时它不起作用

request.session.set_test_cookie()

然后它设置了 cookie 但 response.set_cookie 函数没有设置 cookie。这段代码我试过了。

def index(request):
    if request.method == 'GET':
        response = HttpResponse('hello')
        days_expire = 7
        max_age = days_expire * 24 * 60 * 60 
        response.set_cookie('my_cookie', 'Product Cart', max_age=max_age)
        return render(request, 'home/index.py')

为了获取 cookie,正在使用此代码

def sport(request):
    if request.method == 'GET':
        if 'my_cookie' in request.COOKIES:
            value = request.COOKIES['my_cookie']
            return HttpResponse(value)
        else:
            return HttpResponse('Cookie not set')

它总是打印cookie not set string,这可能是什么原因。

【问题讨论】:

标签: python django cookies


【解决方案1】:

您正在创建两个不同的HttpResponse 实例:一个手动创建,另一个由render() 调用创建并从视图返回。 您应该保存 render() 调用的结果并将 cookie 设置在那里:

response = render(request, 'home/index.py')
response.set_cookie('my_cookie', 'Product Cart', max_age=max_age)
return response

您还应该考虑:

  • 为您的模板使用不同于.py 的扩展名。他们可能会对 Python 代码文件感到困惑。
  • 使用sessions 作为您的送货卡。

【讨论】:

  • 非常感谢,它解决了我的问题,非常感谢:)
  • 我如何使用“字典”代替 my_cookie 变量,如 my_cookie.item_count 和 my_cookie.price
  • Cookies 只是文本,它们不能直接存储字典,但是会话可以做到这一点。如果您需要更多信息,请使用新主题打开一个新问题。
猜你喜欢
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 2012-03-09
  • 2013-08-08
  • 2018-11-03
相关资源
最近更新 更多