The other day I wrote about turning off browser caching when a user is logged in. Since I’m apparently a clueless n00b, it only occurred to me later that this is the sort of thing belongs in middleware. That way you don’t have to modify individual views, and it works for flatpages as well. Here’s the middleware; it should go in MIDDLEWARE_CLASSES before sessions and flatpages:
import re def _add_to_header(response, key, value): if response.has_header(key): values = re.split(r'\s*,\s*', response[key]) if not value in values: response[key] = ', '.join(values + [value]) else: response[key] = value def _nocache_if_auth(request, response): if request.user.is_authenticated(): _add_to_header(response, 'Cache-Control', 'no-store') _add_to_header(response, 'Cache-Control', 'no-cache') _add_to_header(response, 'Pragma', 'no-cache') return response class NoCacheIfAuthenticatedMiddleware(object): def process_response(self, request, response): try: return _nocache_if_auth(request, response) except: return response
Oh, and an annoying note: it’s still possible for firefox to keep an authenticated page cached, I can get that to happen with a sequence of Back and Reloads. Maybe that’s because the Back button is trying to respect history rather than the cache? Oh well, I told you not to mistake this for a security fix.