27

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

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

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.

4

5 回答 5

34

这是如何做到的:

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
于 2013-06-27T04:57:38.417 回答
6

如果您只需要在渲染模板时设置 cookie 值,您可以尝试以下操作:

def view(request, template):
    # Manually set the value you'll use for rendering
    # (request.COOKIES is just a dictionnary)
    request.COOKIES['key'] = 'val'
    # Render the template with the manually set value
    response = render(request, template)
    # Actually set the cookie.
    response.set_cookie('key', 'val')

    return response
于 2016-06-22T02:37:14.113 回答
5

接受的答案会在模板呈现之前设置 cookie。这行得通。

response = HttpResponse()
response.set_cookie("cookie_name", "cookie_value")
response.write(template.render(context))
于 2016-04-29T09:48:43.540 回答
0
                response = render(request, 'admin-dashboard.html',{"email":email})
                #create cookies
                expiry_time = 60 * 60 #in seconds
                response.set_cookie("email_cookie",email,expiry_time);
                response.set_cookie("classname","The easylearn academy",expiry_time);
于 2021-08-11T08:49:07.360 回答
-1
def index(request, template):
    response = HttpResponse('blah')
    response.set_cookie('id', 1)
    id = request.COOKIES.get('id')
    return render_to_response(template,{'cookie_id':id})
于 2013-06-12T04:25:52.640 回答