OpenGraph+ reads HTTP cache headers from your Django responses to decide when to re-render social card images. Django has built-in support for cache headers, so this is straightforward.
This page covers the Django side. For how OpenGraph+ handles caching at the HTTP level, see the HTTP Caching guide.
@cache_control decorator
The most direct way to set cache headers on a view:
from django.views.decorators.cache import cache_control
@cache_control(max_age=86400, public=True)
def blog_post(request, slug):
post = get_object_or_404(Post, slug=slug)
return render(request, 'blog/post.html', {'post': post})
This sets Cache-Control: public, max-age=86400. OpenGraph+ serves the cached image for 24 hours without hitting your server.
Class-based views
Use method_decorator to apply @cache_control to class-based views:
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control
from django.views.generic import DetailView
@method_decorator(cache_control(max_age=86400, public=True), name='dispatch')
class PostDetailView(DetailView):
model = Post
ConditionalGetMiddleware
Add django.middleware.http.ConditionalGetMiddleware to your MIDDLEWARE setting for automatic ETag support. This middleware calculates ETags from response content and handles conditional requests automatically.
# settings.py
MIDDLEWARE = [
# ...
'django.middleware.http.ConditionalGetMiddleware',
]
If your content hasn’t changed, Django returns 304 Not Modified and OpenGraph+ serves the cached image.
Manual headers
Set headers directly on the response for full control:
from django.shortcuts import render, get_object_or_404
def blog_post(request, slug):
post = get_object_or_404(Post, slug=slug)
response = render(request, 'blog/post.html', {'post': post})
response['Cache-Control'] = 'public, max-age=3600'
response['ETag'] = f'"{post.updated_at.isoformat()}"'
return response
Recommendations
| Page type | Strategy |
|---|---|
| Static pages | @cache_control(max_age=604800, public=True) |
| Blog posts | @cache_control(max_age=86400, public=True) |
| Index pages | @cache_control(max_age=3600, public=True) |
| User dashboards | @cache_control(no_store=True) |
Meta tag overrides
If you can’t control HTTP headers, use meta tags instead. See the HTTP Caching guide for the full list of meta tag overrides.
Purging cached images
When you need to force a refresh immediately, go to your website dashboard, find the page, and click purge. This clears the cached image and triggers a re-render on the next request.