Managing Cookies in Django

Understanding Django cookies with examples

Goutom Roy
May 21, 2019 · 3 min read
Image for post
Image for post
Photo by John Hoang on Unsplash

HTTP is a stateless protocol so when a request is sent to the server, it does not know whether you are requesting the page for the first time or you are the same user who has visited this page many times before.

This HTTP statelessness was a problem for ecommerce website developers because persistence among requests could be used to recommend products or display products in a shopping cart. To appease this necessity, the cookie was introduced.

A cookie is a small piece of data stored in the user’s browser which is sent by the server. They are commonly used to store user preferences.

This is how cookies work, in general:

  1. The browser sends the request to the server.
  2. The server sends the response along with one or more cookies to the browser.
  3. The browser saves the cookie it received from the server. From now on, the browser will send this cookie to the server every time any request is made to the server until the cookie expires.
  4. When the cookie expires, it is removed from the browser.

Working With Cookies

The Django HttpResponse object has a set_cookie() method.

A syntax of:

set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False, samesite=None) :
  1. name: Name of the cookie.
  2. value: Value you want to store in the cookie. You can set int or string but it will return string.
  3. max_age: Should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session. If expires is not specified, it will be calculated.
  4. expires: Should either be a string in the format "Wdy, DD-Mon-YY HH:MM:SS GMT" or a datetime.datetime object in UTC. If expires is a datetime object, the max_age will be calculated.

Check the complete method definition in the Django docs.

Every Django request object has a COOKIES attribute which is a dictionary. We can use COOKIES to read a cookie value like below, which returns a string even though you set an integer value:

request.COOKIES[‘cookie_name’]

Let’s take an example.

Create a view in your views.py as below:

def test_cookie(request):   
if not request.COOKIES.get('team'):
response = HttpResponse("Visiting for the first time.")
response.set_cookie('team', 'barcelona')
return response
else:
return HttpResponse("Your favorite team is {}".format(request.COOKIES['team']))

Now, add the URL for this view in urls.py.

urlpatterns = [
path('test_cookie/', views.test_cookie, name='test_cookie'),
]

When you browse http://127.0.0.1:8000/test_cookie/ for the first time, it sends the cookie team along with the response and the browser stores it. Here, we did not set max_age so the browser will delete the cookie when the browser is closed.

When cookies are set in the browser with test_cookie or any other requests, each subsequent request to http://127.0.0.1:8000/test_cookie/(or any other pages of http://127.0.0.1:8000/), will send all the cookies to the server.

HttpResponse does not include any cookies unless you do set_cookie().

To view the cookies sent by the server in Google Chrome, hit CTRL+Shift+J, this will open the Developer Console.

To delete a cookie, simply call response.delete_cookie(‘cookie_name’). There is no cookie update method in HttpResponse, use set_cookie() to update the cookie value or expiry time.

  1. Never ever use cookies to store sensitive data like passwords. Cookies store data in plain text, as a result, anybody can read/modify them.
  2. Most browsers don’t allow cookies to store more than 4KB of data (i.e. 4KB for each cookie). Further, most browsers accept no more than 30 cookies per website. Actually, the exact number of cookies per website varies from browser to browser, visit Browser Cookie Limits for more details.
  3. Recall that once the cookie is set in the browser, it will be sent along with each request to the server. Let’s say we have added 20 cookies each of size 4KB, that works out to be 80KB. That means that, with every request to the server, the browser would need to send 80KB of additional data with every request!
  4. Users can delete the cookies at their will. The user can even configure their browsers to not accept cookies at all.

Advice for programmers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store