[Fixed]-Django – Disable Page Level Caching by User

1👍

You can extend the CacheMiddleware provided by django such that the admin users always see fresh content instead of cached.

Have a look at the source code for FetchFromCacheMiddleware, you can see this code snippet:

def process_request(self, request):
    [...]
    if request.method not in ('GET', 'HEAD'):
        request._cache_update_cache = False
        return None  # Don't bother checking the cache.

The if condition here tells django to skip cache and don’t update the existing cached data if the request method is not GET or HEAD.

Similarly, you can add a check where you skip the cache if the user is an admin. Roughly it will look like this:

def process_request(self, request):
    [...snip..]
    if request.user.is_staff:
        request._cache_update_cache = False
        return None  # Don't bother checking the cache.

UPDATE: The cache_page decorator uses django’s CacheMiddleware which extends the functionality of FetchFromCacheMiddleware and UpdateCacheMiddleware.

Now you’ll have to make your own version of CacheMiddleware and cache_page decorator. This custom_cache_page decorator will call your CustomCacheMiddleware which extends your CustomFetchFromCacheMiddleware and django’s UpdateCacheMiddleware.

After you have completed the CustomCacheMiddleware, you’ll have to replace django’s CacheMiddleware with your own. This can be done by changing MIDDLEWARE_CLASSES tuple in settings.py.

👤v1k45

Leave a comment