Django Middleware — ELI5
Imagine a building with security guards at the entrance. When you walk in, the first guard checks your ID. The second guard scans your bag. The third guard gives you a visitor badge. Only after passing all three do you reach the office you came for.
When you leave, you pass the same guards in reverse order. The badge guard takes your badge back. The bag guard waves you through. The ID guard says goodbye.
Django middleware works exactly like those guards. Every time someone visits your website, their request passes through a chain of middleware — each one can inspect, modify, or even reject the request before it reaches your view (the actual page logic). On the way back out, the response passes through the same chain in reverse, and each middleware can modify the response too.
Django comes with built-in middleware that handles common tasks. One adds security headers to protect against attacks. Another manages user sessions so your app remembers who’s logged in. A third checks for cross-site request forgery — a type of hack where a malicious site tricks your browser into submitting forms on another site.
You can also write your own middleware. Want to log how long every page takes to load? That’s a middleware job. Want to block requests from certain countries? Middleware. Want to add a custom header to every response? Middleware again.
The order matters — just like security guards, the first middleware in the list runs first on the way in and last on the way out.
The one thing to remember: Middleware is Django’s assembly line — every request and response passes through it, getting checked and modified at each step.
See Also
- Python Django Admin Get an intuitive feel for Django Admin so Python behavior stops feeling unpredictable.
- Python Django Basics Get an intuitive feel for Django Basics so Python behavior stops feeling unpredictable.
- Python Django Celery Integration Why your Django app needs a helper to handle slow jobs in the background.
- Python Django Channels Websockets How Django can send real-time updates to your browser without you refreshing the page.
- Python Django Custom Management Commands How to teach Django new tricks by creating your own command-line shortcuts.