I could set the cookies with response.set_cookie() and response.cookies[]
as shown below. *I use Django 4.2.1:
# "my_app1/views.py"
from django.http import HttpResponse
def test(request):
response = HttpResponse('Test')
response.set_cookie('first_name', 'John') # Here
response.cookies['last_name'] = 'Smith' # Here
return response
Then, I could only delete response.set_cookie()
's cookie first_name
rather than response.cookies[]
's cookie last_name
with response.delete_cookie() as shown below:
# "my_app1/views.py"
from django.http import HttpResponse
def test(request):
response = HttpResponse('Test')
response.delete_cookie('first_name') # Deleted
response.delete_cookie('last_name') # Undeleted
return response
So, what is the difference between response.set_cookie()
and response.cookies[]
in Django?
response.set_cookie() always sets a cookie with the global path
/
if not specifying a path as an argument as shown below. *I recommend to basically use it without specifying a path as an argument because it's simple and consistent always setting a cookie with the global path/
.response.cookies[]
sets a cookie with the current url's path which can be/
,/my_app1
or others depending as shown below. *I don't recommend to basically use it because it's not simple and consistent setting a cookie with the current url's path which is kind of random.And, response.delete_cookie() deletes the cookie of the global path
/
if not specifying a path as an argument. So to deleteresponse.cookies[]
's cookielast_name
, you need to specify/my_app1
as an argument as shown below:Then, both
response.set_cookie()
's cookiefirst_name
andresponse.cookies[]
's cookielast_name
are deleted as shown below: