Django Cookies

cookie is a small piece of information stored on the client-side by a web browser. Max size of a cookie is 4KB and most web browsers allow up to 20 cookies per website. Cookie information gets added to the request.

A cookie can have an expiry date and time after which it automatically gets removed. A cookie may also be set to expire with the browser session.

Cookie Methods

Django provides built-in methods to set, update, fetch and delete cookies.

set_cookie('cookie_name', 'cookie-value')

get('cookie_name')

get() and set_cookie()

To create or update cookie add the code below in views.py

    from django.http import HttpResponse
    
    def setcookie(request):  
        response = HttpResponse("Welcome Guest.")  
        response.set_cookie('programink', 'We love Django')  
        return response  
                                

To get cookie information to add the code below in views.py

    def getcookie(request):  
        info  = request.COOKIES.get('programink') 
        return HttpResponse("Welcome Back." +  info);  
                                

Also, add a matching URL path under app > urls.py

    from django.urls import path  
    from . import views  
    
    urlpatterns = [  
        ...
        path('setcookie',views.setcookie),  
        path('getcookie',views.getcookie)  
    ]  
                                

On the first visit to the URL response will be:

Welcome Guest.

On re-visiting to the URL response will be:

Welcome Back. We love Django

Cookie Expiry Timestamp

set_cookie(key, value='', max_age=None, expires=None)

  • max_age: Should be a number of seconds, or None if the cookie should last only as long as the client’s browser session.
  • expires: Should either be a string in the format "Wdy, DD-Mon-YY HH:MM:SS GMT" or a datetime.datetime object in UTC.