Django Cookies

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

Cookie can have an expiry date and time after which it automatically gets removed. Cookie may also be set to expire with brower 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 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 first visit to the url response will be:

Welcome Guest.

On re-visiting to the url response will be:

Welcome Back. We love Django