Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cookie in Django and then render template?

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.

like image 673
Jim Avatar asked Jun 12 '13 04:06

Jim


People also ask

Does Django use cookies by default?

If SESSION_EXPIRE_AT_BROWSER_CLOSE is set to True , Django will use browser-length cookies – cookies that expire as soon as the user closes their browser. Use this if you want people to have to log in every time they open a browser.

Where are Django cookies?

Build Python Django Real Project: Django Web Development Always keep in mind, that cookies are saved on the client side and depending on your client browser security level, setting cookies can at times work and at times might not.


3 Answers

This is how to do it:

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 
like image 160
Jim Avatar answered Sep 17 '22 16:09

Jim


If you just need the cookie value to be set when rendering your template, you could try something like this :

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 
like image 36
vmonteco Avatar answered Sep 16 '22 16:09

vmonteco


The accepted answer sets the cookie before the template is rendered. This works.

response = HttpResponse()
response.set_cookie("cookie_name", "cookie_value")
response.write(template.render(context))
like image 21
James Doe 33 Avatar answered Sep 17 '22 16:09

James Doe 33