How to set cookie in Django and then render template?
This is how to do it:
from django.shortcuts import renderdef 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))