Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django prevent caching view if user is logged in

My visitors get a cached version of the page from Varnish. I would like the admin user to see the current version of the page all times. This way, all changes are directly visible.

Does someting like that exist? I'm aware of the @never_cache decorator. I'm looking for something like that, only if the user is not logged in.

Bonus points if it works with Django-CMS!

like image 736
vdboor Avatar asked Dec 16 '22 09:12

vdboor


1 Answers

I assumed that you're using cache decorators. The code below is a decorator that returns a view decorated with another decorator (i.e. cache_page) only if user is not admin. So admin will always get the non-decorated (non-cached) page, and other users will get decorated (so possibly cached) page. It works with all possible decorators (not only with the 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 typical syntax:

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

use:

@conditional_cache(decorator=cache_page(123))  # The argument is what you usually do with views, but without the @
def testview(request):
    (...)
like image 133
Mariusz Jamro Avatar answered Jan 02 '23 07:01

Mariusz Jamro