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() and set_cookie()

To create or update cookie add the code below in

    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

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

Also add a matching url path under app >

    from django.urls import path  
    from . import views  
    urlpatterns = [  

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