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
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 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.