如何在Django中设置cookie然后渲染模板? [英] How to set cookie in Django and then render template?

查看:26
本文介绍了如何在Django中设置cookie然后渲染模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在视图中设置一个 cookie,然后让该视图呈现一个模板.据我了解,这是设置 cookie 的方法:

I want to set a cookie inside a view and then have that view render a template. As I understand it, this is the way to set a cookie:

def index(request):
    response = HttpResponse('blah')
    response.set_cookie('id', 1)
    return response

但是,我想设置一个cookie然后渲染一个模板,像这样:

However, I want to set a cookie and then render a template, something like this:

def index(request, template):
    response_obj = HttpResponse('blah')
    response_obj.set_cookie('id', 1)
    return render_to_response(template, response_obj)   # <= Doesn't work

模板将包含链接,单击这些链接时将执行检查我设置的 cookie 的其他视图.执行我在上面第二个示例中展示的操作的正确方法是什么?我知道我可以为我的模板创建一个包含所有 HTML 的字符串并将该字符串作为参数传递给 HttpResponse 但这看起来真的很难看.没有更好的方法来做到这一点吗?谢谢.

The template will contain links that when clicked will execute other views that check for the cookie I'm setting. What's the correct way to do what I showed in the second example above? I understand that I could create a string that contains all the HTML for my template and pass that string as the argument to HttpResponse but that seems really ugly. Isn't there a better way to do this? Thanks.

推荐答案

这是怎么做的:

from django.shortcuts import render

def home(request, template):
    response = render(request, template)  # django.http.HttpResponse
    response.set_cookie(key='id', value=1)
    return response

这篇关于如何在Django中设置cookie然后渲染模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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