How to Use cache_page Decorator in Django for View Caching
Use Django's
cache_page decorator to cache the output of a view for a specified number of seconds. Apply it by importing from django.views.decorators.cache and decorating your view function with @cache_page(timeout_in_seconds).Syntax
The cache_page decorator caches the entire output of a view for a given timeout period in seconds. It is imported from django.views.decorators.cache. You apply it by placing @cache_page(timeout) above your view function or method.
- timeout: Number of seconds to cache the view output.
- Works with function-based views and class-based views (using
method_decorator).
python
from django.views.decorators.cache import cache_page @cache_page(60 * 15) # Cache for 15 minutes def my_view(request): # view logic here pass
Example
This example shows a simple Django view that returns the current time. Using cache_page caches the response for 10 seconds, so repeated requests within that time return the cached time instead of recalculating.
python
from django.http import HttpResponse from django.views.decorators.cache import cache_page import datetime @cache_page(10) # Cache for 10 seconds def current_time(request): now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') return HttpResponse(f"Current time is: {now}")
Output
Current time is: 2024-06-01 12:00:00 (same output for 10 seconds)
Common Pitfalls
- Not setting a cache backend in Django settings causes caching to silently fail.
- Using
cache_pageon views with user-specific data can cause wrong data to be shown to users. - For class-based views, forgetting to use
method_decoratorto applycache_pageon dispatch method.
python
from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from django.views import View from django.http import HttpResponse # Wrong: applying cache_page directly on class # @cache_page(60) # class MyView(View): # def get(self, request): # return HttpResponse('Hello') # Correct way: @method_decorator(cache_page(60), name='dispatch') class MyView(View): def get(self, request): return HttpResponse('Hello')
Quick Reference
Summary tips for using cache_page:
- Always configure a cache backend in
settings.py. - Use appropriate timeout values based on how often data changes.
- Do not cache views that return user-specific or sensitive data.
- For class-based views, use
method_decoratorondispatch.
Key Takeaways
Use @cache_page(timeout) to cache a view's output for the given seconds.
Configure a cache backend in Django settings for caching to work.
Avoid caching views with user-specific or sensitive data.
Use method_decorator to apply cache_page on class-based views.
Choose timeout values wisely based on data update frequency.