4

I'm using django caching(per-site cache using middlewares), and want to show cached pages only to anonymous users.

I found an option:

CACHE_MIDDLEWARE_ANONYMOUS_ONLY

and set it True.

It cases that page generated for logged user will not be saved to cache, but pages generated for anonymous are saved to cache and send to logged users.

How to force django to not serve cached content to logged users? I'm using user login information on each page(like: "hi UserName"), and when anonymous user request a page it's cached and since this logged users got: "Hi anonymous!"

Sorry for my bad english. John.

qraq
  • 318
  • 3
  • 11

1 Answers1

5

It seems that what you need is vary decorators. For example you can use this code:

from django.views.decorators.vary import vary_on_headers

@vary_on_headers('Cookie')
def my_view(request):
    # do some stuff

Or equivalently

from django.views.decorators.vary import vary_on_cookie

@vary_on_cookie
def my_view(request):
    # do some stuff

The response will be cached unless cookies change (this happens when for example a user logges in). There are other interesting things you can do with vary. See this article or the documentation for more details.

You can also try doing this in a custom middleware so you won't have to add these decorators on every view. This can be done like this:

from django.utils.cache import add_never_cache_headers

class DisableClientSideCachingMiddleware(object):
    def process_response(self, request, response):
        if request.user.is_authenticated():
            add_never_cache_headers(response)
        return response

I've borrowed the code from here. Now you only add the middleware and you don't have to worry about anything else.

Community
  • 1
  • 1
freakish
  • 54,167
  • 9
  • 132
  • 169