You can set cookies 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 question and my answer which explain why to use response.set_cookie() rather than response.cookies[]
to set cookies and I asked the question about how to set a dictionary or list to a cookie and get it properly and you can see my answer explaining how to delete cookies.
render() and set_cookie():
from django.shortcuts import render
def my_view(request):
response = render(request, 'index.html', {})
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):
rts = render_to_string('index.html', {})
response = HttpResponse(rts)
response.set_cookie('name', 'John')
response.cookies['age'] = 27
return response # Must return the object
HttpResponse() and set_cookie():
from django.http import HttpResponse
def my_view(request):
response = HttpResponse('View')
response.set_cookie('name', 'John')
response.cookies['age'] = 27
return response # Must return the object
redirect() and set_cookie():
from django.shortcuts import redirect
def my_view(request):
response = redirect('https://example.com/')
response.set_cookie('name', 'John')
response.cookies['age'] = 27
return response # Must return the object
HttpResponseRedirect() and set_cookie():
from django.http import HttpResponseRedirect
def my_view(request):
response = HttpResponseRedirect('https://example.com/')
response.set_cookie('name', 'John')
response.cookies['age'] = 27
return response # Must return the object
And, you can get the cookies with request.COOKIES['key'] and request.COOKIES.get('key') as shown below. *request.COOKIES.get()
returns None
by default if the key doesn't exist and you can change None
to other value like Doesn't exist
by setting it to the 2nd argument as shown below:
from django.shortcuts import render
def my_view(request):
print(request.COOKIES['name']) # John
print(request.COOKIES.get('age')) # 27
print(request.COOKIES.get('gender')) # None
print(request.COOKIES.get('gender', "Doesn't exist")) # Doesn't exist
return render(request, 'index.html', {})
And, you can get cookies with request.COOKIES.key
in Django Templates as shown below:
# "templates/index.html"
{{ request.COOKIES.name }} {# John #}
{{ request.COOKIES.age }} {# 27 #}
And, you can delete the cookies with response.delete_cookie() as shown below. *You must return the object otherwise cookies are not deleted from a browser:
from django.shortcuts import render
def my_view(request):
response = render(request, 'index.html', {})
response.delete_cookie('name')
response.delete_cookie('age')
return response # Must return the object