python
17 lines · 4 steps
Busting template fragment caches in Django
A signal receiver clears cached template fragments whenever an Article is saved or deleted.
Explained by
highlit
1from django.core.cache import cache
2from django.core.cache.utils import make_template_fragment_key
3from django.db.models.signals import post_save, post_delete
4from django.dispatch import receiver
5
6from .models import Article
7
8
9@receiver(post_save, sender=Article)
10@receiver(post_delete, sender=Article)
11def invalidate_article_fragments(sender, instance, **kwargs):
12 keys = [
13 make_template_fragment_key("article_detail", [instance.pk]),
14 make_template_fragment_key("article_sidebar", [instance.category_id]),
15 make_template_fragment_key("article_list"),
16 ]
17 cache.delete_many(keys)
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Signals let you react to model lifecycle events without touching every save site.
- 2Template fragment keys are reconstructible from the same arguments used in the template, so you can target exactly what to invalidate.
- 3Deleting stale cache entries on write keeps cached HTML consistent with the database.
Related explainers
python
import hashlib from collections import defaultdict from pathlib import Path
Finding duplicate files by size then hash
hashing
file-io
deduplication
Intermediate
7 steps
python
from flask import Flask, request, g, jsonify from flask_babel import Babel, gettext as _, format_datetime from datetime import datetime
Per-request localization in Flask with Babel
i18n
content-negotiation
request-lifecycle
Intermediate
8 steps
php
<?php namespace App\Http\Middleware;
Caching HTTP responses with Laravel middleware
middleware
caching
http
Intermediate
8 steps
python
from datetime import datetime, timezone _INTERVALS = ( ("year", 60 * 60 * 24 * 365),
Building a human-friendly time_ago helper
datetime
timezones
formatting
Intermediate
5 steps
python
import time import threading from flask import Flask, request, jsonify, g
A token-bucket rate limiter in Flask
rate-limiting
token-bucket
middleware
Intermediate
7 steps
php
<?php namespace App\Http\Controllers;
A cached autocomplete endpoint in Laravel
caching
validation
query-ranking
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/busting-template-fragment-caches-in-django-explained-python-23b2/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.