response.set_cookie() vs response.cookies[] in Django

267 views Asked by At

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

enter image description here

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

enter image description here

So, what is the difference between response.set_cookie() and response.cookies[] in Django?

1

There are 1 answers

0
Super Kai - Kazuya Ito On
  • 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.

enter image description here

And, response.delete_cookie() deletes the cookie of the global path / if not specifying a path as an argument. So to delete response.cookies[]'s cookie last_name, you need to specify /my_app1 as an argument as shown below:

# "my_app1/views.py"

from django.http import HttpResponse

def test(request):
    response = HttpResponse('Test')
    response.delete_cookie('first_name')
    response.delete_cookie('last_name', '/my_app1')
    return response                    # ↑ Here ↑

Then, both response.set_cookie()'s cookie first_name and response.cookies[]'s cookie last_name are deleted as shown below:

enter image description here