About Caching Only Anonymous Visits
To make sure that user navigation or widgets are not cached and shown for other users, it's important to cache only anonymous visits.
You can do that with this decorator:
# myproject/apps/utils/caching.py
from django.views.decorators.cache import cache_page
def cache_page_for_anonymous(timeout, **kwargs):
def decorator(view_func):
cached_view = cache_page(timeout, **kwargs)(view_func)
@wraps(view_func)
def wrapper(request, *args, **kw):
if request.user.is_authenticated:
return view_func(request, *args, **kw)
return cached_view(request, *args, **kw)
return wrapper
return decorator
Then cache the view as follows:
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.models import User
from myproject.apps.utils.caching import cache_page_for_anonymous
@cache_page_for_anonymous(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)
Tips and Tricks Programming Caching Django 6.x Django 5.2 Django 4.2 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.
Also by me
Django Messaging
For Django-based social platforms.
Django Paddle Subscriptions
For Django-based SaaS projects.
Django GDPR Cookie Consent
For Django websites that use cookies.