About Cache Invalidation for URL Path

When you have views cached with the @cache_page decorator, after updates, you will want to invalidate the cache. Here is a utility function to do that:

def invalidate_cache_for_url(url_path):
    """Delete the cache_page header key for a given URL path.

    Mirrors Django's _generate_cache_header_key so the correct cache entry
    is removed without needing a live request object.
    """
    import hashlib
    from django.core.cache import cache

    website_url = getattr(settings, "WEBSITE_URL", "")
    if not website_url:
        return

    full_url = website_url.rstrip("/") + url_path
    url_hash = hashlib.md5(
        full_url.encode("ascii"),
        usedforsecurity=False,
    ).hexdigest()

    key_prefix = getattr(settings, "CACHE_MIDDLEWARE_KEY_PREFIX", "")
    cache_key = f"views.decorators.cache.cache_header.{key_prefix}.{url_hash}"

    if settings.USE_I18N or settings.USE_L10N:
        cache_key += f".{settings.LANGUAGE_CODE}"
    if settings.USE_TZ:
        cache_key += f".{settings.TIME_ZONE}"

    cache.delete(cache_key)

To use this function, run it in the form views or post-save signal handlers:

invalidate_cache_for_url(
    reverse("tricks:trick_details", kwargs={"trick_id": instance.pk})
)
invalidate_cache_for_url(
    reverse("tricks:trick_list")
)

The function assumes that you have WEBSITE_URL setting pointing to your host in the project settings, e.g.:

WEBSITE_URL = "https://www.djangotricks.com"

Tips and Tricks Programming Caching Memcached Redis Cache

Django/Python Consulting

If you have a specific Django challenge or integration you'd like to solve, I'd be happy to help. Book a free 30-minute call to discuss your project, see if we're a good fit, and explore the best approach for your needs. After the call, you'll receive a tailored cost estimate based on what we discuss.