About Invalidating Django Page Cache

Use the following utility function to delete cache for a specific view cached with @cache_page decorator:

def invalidate_view_cache(
    view_name, 
    scheme="http", host="127.0.0.1:8000", 
    args=None, kwargs=None,
):
    from django.urls import reverse
    from django.http import HttpRequest
    from django.core.cache import cache
    from django.utils.cache import get_cache_key

    args = args or []
    kwargs = kwargs or {}

    url_path = reverse(view_name, args=args, kwargs=kwargs)

    dummy_request = HttpRequest()
    dummy_request.path = url_path
    dummy_request.scheme = scheme
    dummy_request.META = {"HTTP_HOST": host}

    if key := get_cache_key(dummy_request):
        cache.delete(key)

So if you have a view:

from django.shortcuts import render, get_object_or_404
from django.views.decorators.cache import cache_page
from django.contrib.auth.models import User

@cache_page(60 * 15)  # Cache the view for 15 minutes
def user_profile_view(request, username):
    user = get_object_or_404(User, username=username)
    context = {
        "user": user,
    }
    return render(request, "pages/user_profile.html", context)

And URL path:

from django.urls import path
from .views import user_profile_view

urlpatterns = [
    path("users/<str:username>/", user_profile_view, name="user_profile"),
]

And that user changes their user information, you can invalidate the cache and make the page show fresh information with:

invalidate_view_cache("user_profile", kwargs={"username": user.username})

Tips and Tricks Programming Django 5.2 Django 4.2 Django 3.2 Memcached Redis