Search code examples
djangocachingdjango-viewsbrowser-cache

How to set cache control headers in a Django view class (no-cache)


Now this took me some time to figure out, so I will self-answer it. I wanted to disable browser caching for one specific page in Django on a View. There is some information how to do this if the view is a function, but not if it's a class. I did not want to use a middleware, because there was only one specific view that I didn't want to be cached.


Solution

  • There are decorators to do this, for example cache_control and never_cache in django.views.decorators.cache

    For a function, you would just decorate the function like this

    @never_cache
    def my_view1(request):
        # your view code
    
    @cache_control(max_age=3600)
    def my_view2(request):
        # your view code
    

    see here https://docs.djangoproject.com/en/3.0/topics/cache/#controlling-cache-using-other-headers

    Now, if your view is a class, you have to apply another method, that I already knew of for using authentication, but did not make the connection. There is another decorator for the class to decorate functions within the class

    from django.utils.decorators import method_decorator
    from django.views.decorators.cache import never_cache
    
    decorators = [never_cache,]
    
    @method_decorator(decorators, name='dispatch')
    class MyUncachedView(FormView):
        # your view code
    

    This will decorate the form method dispatch with the decorators specified in the decorators list, defined above. You don't have to implement the dispatch method, btw.

    There are also other variations to do that, see here: https://docs.djangoproject.com/en/3.0/topics/class-based-views/intro/#decorating-the-class