![]() |
VOOZH | about |
Middleware in Django acts as lightweight components placed between the web server and the views. They process requests and responses globally, helping manage common tasks without complicating view code.
Django integrates middleware at multiple stages of the request-response cycle:
1. Request Phase: The request passes through each middleware in the order defined in the MIDDLEWARE setting (top-to-bottom). Middleware can:
2. URL Resolution and View Processing: After passing the middleware stack, the request reaches Django's URL resolver, which executes the matched view function or class-based view to generate a response.
3. Response Phase: The response passes back through the middleware stack in reverse order (bottom-to-top). Middleware can:
4. Exception Handling (Optional):
If an exception occurs during view processing, a process_exception hook in middleware can intervene before the response phase.
This structure ensures that middleware can inject functionality at multiple points in the request-response lifecycle while remaining modular, reusable, and decoupled from individual views.
Hooks are special methods in Django middleware that are called at specific points during the request-response cycle. They allow inspection, modification, or short-circuiting of requests and responses in a modular and reusable way.
Django's middleware can be divided into 2 types: built-in and custom.
Django includes a robust set of built-in middleware classes, enabled by default in new projects. Below is a comprehensive overview including their purposes and key settings:
| Middleware Class | Purpose | Key Settings |
|---|---|---|
| SecurityMiddleware | Adds security headers (e.g., HSTS, X-Content-Type-Options); redirects HTTP to HTTPS. | SECURE_HSTS_SECONDS, SECURE_SSL_REDIRECT. Use in production. |
| SessionMiddleware | Enables session handling; attaches session data to requests. | Requires SESSION_ENGINE; place before AuthenticationMiddleware. |
| CsrfViewMiddleware | Protects against CSRF attacks by validating tokens in POST/PUT/DELETE requests. | CSRF_TRUSTED_ORIGINS; exempt views with @csrf_exempt. |
| XFrameOptionsMiddleware | Prevents clickjacking by setting X-Frame-Options header. | X_FRAME_OPTIONS (e.g., 'DENY'). |
| CommonMiddleware | Handles ETags for conditional GETs, redirects for trailing slashes/www, and gzip compression hints. | APPEND_SLASH, USE_ETAGS. Place before GZipMiddleware. |
| AuthenticationMiddleware | Populates request.user; requires sessions. | Place after SessionMiddleware. |
| MessageMiddleware | Attaches messages (e.g., from messages.success()) to requests for display. | Works with django.contrib.messages. |
| FetchFromCacheMiddleware | Retrieves responses from cache if available (pairs with UpdateCacheMiddleware). | Requires caching backend. |
| UpdateCacheMiddleware | Caches responses post-view. | Place at ends of MIDDLEWARE for full coverage. |
| ConditionalGetMiddleware | Supports HTTP 304 (Not Modified) for ETag/Last-Modified checks. | Enhances performance. |
| GZipMiddleware | Compresses responses for clients that support gzip. | Place after CommonMiddleware. |
| LocaleMiddleware | Enables i18n by setting request.LANGUAGE_CODE from URL/path/cookie. | Requires USE_I18N=True. |
| StaticFilesMiddleware | Serves static/media files in development (use collectstatic in production). | Only for DEBUG=True; place last. |
The default MIDDLEWARE in settings.py includes most of these. Customize as needed, but maintain order for dependencies (e.g., sessions before auth).
Example:
Custom middleware allows the implementation of application-specific logic that isn’t covered by Django’s built-in middleware. Django supports two approaches for creating custom middleware:
1. Class-based Middleware
2. Function-based Middleware
Suppose a Django project has three types of users: Teacher, Student, and Principal. The goal of the middleware is to redirect users to their respective home pages after login:
Consider a project named 'projectmiddleware' having an app named 'testapp'.
This file manages user authentication, user registration, and user-specific homepages, acting as the central component for handling user interactions.
This file defines a custom user model, CustomUser, which extends Django’s AbstractUser. It adds a role field to categorize users as teacher, student, or principal, enabling role-based behavior and access control within the application.
This Django file defines a custom user creation form, CustomUserCreationForm, which extends UserCreationForm. It includes a role field, allowing users to select their role (teacher, student, or principal) during registration. This ensures consistency with the role-based functionality of the custom user model.
This Django middleware, CustomMiddleware, injects custom logic into the request-processing flow. It intercepts requests for login, logout, and the admin panel, handling them appropriately. For authenticated users, it redirects them to their designated home page based on their role (teacher, student, or principal), ensuring a role-specific navigation experience.
This Django admin configuration manages the CustomUser model within the admin panel. It customizes the displayed fields and registers the model, allowing administrators to efficiently manage users and their roles.
This Django URL configuration maps incoming URLs to the appropriate view functions within the testapp application. It defines routes for admin access, user authentication, and role-based home pages, ensuring that each URL points to its corresponding view logic.
home.html: This is a homepage created in HTML.
login.html: This is the login page which is used to collect the credentials from the user and then pass them to the backend.
signup.html: This is the signup page which is used to collect the credentials from the user and then register the user.
student.html: This is the homepage for student.
teacher.html: This is the homepage for Teacher.
principal.html: This is the homepage for principal.
Apply migrations to set up the database:
python manage.py makemigrations
python manage.py migrate
Start the development server:
python3 manage.py runserver
This will launch the Django application locally, allowing you to access it via the default URL http://127.0.0.1:8000/.
Output Video: