[Django]-How to set cookie for many views?

9πŸ‘

βœ…

You can write custom middleware to achieve your goal as you have many views and of course you can not update every view. The custom middleware would be something like this:

class MyCookieProcessingMiddleware(object):

    # your desired cookie will be available in every django view
    def process_request(self, request):
        # will only add cookie if request does not have it already
        if not request.COOKIES.get('your_desired_cookie'):
            request.COOKIES['set_your_desired_cookie'] = 'value_for_desired_cookie'

    # your desired cookie will be available in every HttpResponse parser like browser but not in django view
    def process_response(self, request, response):
        if not request.COOKIES.get('your_desired_cookie'):
            response.set_cookie('set_your_desired_cookie', 'value_for_desired_cookie')
        return response

In your settings.py file, just add the path to your custom middleware like this:

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'MyProject.myapp.mymodule.MyCookieProcessingMiddleware',  # path to custom class
)

The order of middleware is important and yours belongs after SessionMiddleware.

πŸ‘€Ali Kazi

1πŸ‘

What I understood is that, you want to set the cookie once and then want to check it’s value in any view. If this is your problem then you can save cookie once in views like this:

from project.settings import IS_COOKIE_SET # Set Global value for cookie
response = render_to_response("your-template.html")
if !IS_COOKIE_SET:  
    response.set_cookie('key', 'value')
    return response
else:
    return response

You can check the value of cookie in any other view like this:

request.COOKIES.get('key', None) # Return None If cookie not exists
πŸ‘€fakhir hanif

Leave a comment