Django prevents browsing caching if user is logged in

My visitors get a cached version of the page from Varnish. I would like the admin user to view the current version of the page all the time. Thus, all changes are visible directly.

Is there any similarity? I know the @never_cache decorator. I am looking for something like this only if the user is not logged in.

Bonus points if it works with Django-CMS!

+4
source share
3 answers

I found out that there is something like:

 CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True 

This should work on most websites if there is no difference between users and employees.

To explicitly send the Cache-Control header to employees, you can write some middleware (which also changes to a Cookie header).

+1
source

I suggested that you use cache decorators. The code below is a decorator that returns a view decorated with another decorator (i.e. cache_page ) only if the user is not an administrator. Thus, the administrator will always receive a non-decorated (not cached) page, and other users will receive a decorated (possibly cached) page. It works with all possible decorators (not just cache_page ).

 def conditional_cache(decorator): """ Returns decorated view if user is not admin. Un-decorated otherwise """ def _decorator(view): decorated_view = decorator(view) # This holds the view with cache decorator def _view(request, *args, **kwargs): if request.user.is_staff: # If user is staff return view(request, *args, **kwargs) # view without @cache else: return decorated_view(request, *args, **kwargs) # view with @cache return _view return _decorator 

To use it instead of the usual syntax:

 @cache_page(123) def testview(request): (...) 

using:

 @conditional_cache(decorator=cache_page(123)) # The argument is what you usually do with views, but without the @ def testview(request): (...) 
+8
source

CACHE_MIDDLEWARE_ANONYMOUS_ONLY is removed in Django 1.8

Instead, the headers can be used and, more specifically, the vary_on_cookie decorator.

This means that a separate cache is stored according to each user's cookie.

The recorded users have a cookie, not logins, so different caches are created for each cookie session. The following is my implementation.

urls.py entry:

 from django.views.decorators.vary import vary_on_cookie from django.views.decorators.cache import cache_page ... url( r'^$', cache_page(60 * 1440, cache='disk')(vary_on_cookie(MyCbvView.as_view())), name='view-name', ), ... 
0
source

All Articles