[Django]-How to set cookie and render template in Django?

40πŸ‘

βœ…

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
πŸ‘€Jim

6πŸ‘

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
πŸ‘€vmonteco

5πŸ‘

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))
πŸ‘€James Doe 33

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);

0πŸ‘

You can set cookies and render a template in these ways as shown below. *You must return the object otherwise cookies are not set to a browser different from Django sessions which can set the session id cookies to a browser without returning the object and you can see my answer explaining how to set and get cookies in Django.

render() and set_cookie():

from django.shortcuts import render

def my_view(request, template):
    response = render(request, template)
    response.set_cookie('name', 'John')
    response.cookies['age'] = 27
    return response # Must return the object

render_to_string(), HttpResponse() and set_cookie():

from django.template.loader import render_to_string
from django.http import HttpResponse

def my_view(request, template):
    rts = render_to_string(template)
    response = HttpResponse(rts)
    response.set_cookie('name', 'John')
    response.cookies['age'] = 27
    return response # Must return the object set

-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})
πŸ‘€Manjunath

Leave a comment