如何在Django中设置cookie,然后渲染模板? [英] How to set cookie in Django and then render template?
问题描述
我想在视图中设置一个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的其他视图时, m设定。什么是正确的方法来做我在上面的第二个例子中显示的?我理解,我可以创建一个字符串,其中包含我的模板的所有HTML,并将该字符串作为参数HttpResponse,但这似乎真是丑陋。有没有更好的方法来做到这一点?
The template will contain links which, when clicked will execute other views which which 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屋!