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.
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.
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.
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
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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With