So I have this site (Django 1.8) which has a master template where the name of the logged-in user is displayed, so the template contains
{% if user.is_active %}
{% trans 'Welcome,' %}{% filter force_escape %}{% firstof user.first_name user.username %}{% endfilter %}
{% endif %}
So notice it only displays when the user is active. I now setup caching where I use redis as the cache storage:
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://redis:6379/1',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
},
"KEY_PREFIX": "mycache",
}
}
Caching works correctly, but I notice that also that username is cached in the frontend. This means that when the user loggs off, his name is still visible like he is logged in and even worse, sometimes it displays the name of another user that logged in just before and triggered the caching. It is logical of course as I think the caching framework caches the whole page.
My question is: how do you deal with this? Do I need some user-based caching of some sorts or are there better ways to avoid this? I mean, there must have been other people encountering the same problem?
Given the symptom I assume you're using either the global site cache or the page cache. In both cases, it will indeed keep the whole responses in cache without worrying about the current user or whatever.
What you need here is to use fragment caching and build your cache keys depending on what is user-specific and what's not.