pythondjangocookies

How to disable cookies in Django manually


I know that there are apps for Django to handle cookies, but I want to do it manually. I have a Django application with only two cookies: csrftoken and sessionid.

I want to add a cookie consent banner where the user can block all cookies. How can I do that?


Solution

  • import @csrf_exempt from django.

    from django.views.decorators.csrf import csrf_exempt
    

    To have a view not use csrf tokens do this. (Note: you have to do this for each view that won't have csrf tokens)

    @csrf_exempt
    def viewGoesHere(request):
        pass
    

    And to disable the session cookies you need to replace the middleware. (The thing that makes cookies work). So put this code in there as the code itself.

    from django.contrib.sessions.middleware import SessionMiddleware
    from django.conf import settings
    
    class NewSessionMiddleware(SessionMiddleware):
    
        def process_response(self, request, response):
            response = super(NewSessionMiddleware, self).process_response(request, response)
            # You have access to request.user in this method
            if not request.user.is_authenticated():
                del response.cookies[settings.SESSION_COOKIE_NAME]
            return response
    

    And you need to replace 'myapp.middleware.SessionMiddleware' with 'django.contrib.auth.middleware.AuthenticationMiddleware'

    MIDDLEWARE_CLASSES = (
      'django.middleware.common.CommonMiddleware',
      'myapp.middleware.NewSessionMiddleware', # This is the new middleware
      'django.contrib.auth.middleware.AuthenticationMiddleware',
      'django.middleware.doc.XViewMiddleware',
      'django.contrib.messages.middleware.MessageMiddleware',
      'django.middleware.csrf.CsrfViewMiddleware',
    )