Nips
Nips

Reputation: 13860

How to set cookie for many views?

I have site with many views and I want to check the cookie in each of them, and when it does not - save them. But site have a lot of views.

How to do it only once for all views?

Upvotes: 4

Views: 2486

Answers (2)

Ali Kazi
Ali Kazi

Reputation: 144

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.

Upvotes: 10

fakhir hanif
fakhir hanif

Reputation: 655

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

Upvotes: 1

Related Questions