I can not clear view cache

I use Django 5/Gunicorn/Nginx stack and my relevant cache related settings:

...
MIDDLEWARE = [
    "debug_toolbar.middleware.DebugToolbarMiddleware",
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    "django.middleware.cache.UpdateCacheMiddleware",
    'django.middleware.common.CommonMiddleware',
    "django.middleware.cache.FetchFromCacheMiddleware",
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.memcached.PyMemcacheCache",
        "LOCATION": "127.0.0.1:11211",
    }
}
...

I use @cache_page(60 * 60 * 24 * 30) decorator to cache some of my views, which are expected to change very rarely. But if it changes, it must go live immediately. I tried to clear the cache by the following way resulting no success:

  • Restarting Gunicorn
  • Restart Nginx
  • Reboot the development server
  • Clear the cache from the django shell by cache.clear()

Any idea to solve this is a great help.

Thanks in advance.

Hi,

  1. I think your middlewate ordering is wrong - Check it here: Middleware | Django documentation | Django

So the correct order probably should be:

MIDDLEWARE = [
    "debug_toolbar.middleware.DebugToolbarMiddleware",
    'django.middleware.security.SecurityMiddleware',
    "django.middleware.cache.UpdateCacheMiddleware",
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    "django.middleware.cache.FetchFromCacheMiddleware",
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
  1. You could try the cache_page decorator with a custom cache key. Django’s cache framework | Django documentation | Django
from django.core.cache import cache
from django.views.decorators.cache import cache_page

@cache_page(60 * 60 * 24 * 30, key_prefix='my_view')
def my_view(request):
    # Your view logic here
    # Make sure to update the cache key when the view changes
    cache_key = cache.make_key('my_view', request.GET)
    cache.delete(cache_key)
    # Rest of your view logic