Skip to content

Chapter 7 of 8

Middleware, Security, and File Handling

Middleware in Django is a framework of hooks that processes requests and responses globally. Each middleware is added to the MIDDLEWARE setting in settings.py and is executed in order for requests, then in reverse order for responses. Built-in middleware classes include SecurityMiddleware for HTTPS redirects and HSTS headers, SessionMiddleware for session support, CommonMiddleware for URL rewriting, CsrfViewMiddleware for CSRF protection, AuthenticationMiddleware for attaching request.user, and MessageMiddleware for flash messages. Custom middleware can be created as a factory function returning a callable that wraps request, or by subclassing MiddlewareMixin for the older style with process_request and process_response methods. The ClickjackingMiddleware sets the X-Frame-Options header, while GZipMiddleware compresses responses for browsers that send Accept-Encoding: gzip and must be placed near the top of the middleware list to compress content produced by other components.

Django includes comprehensive built-in security features. CSRF protection uses a token-based system, with the {% csrf_token %} template tag inserting a hidden input bound to the user's session and CsrfViewMiddleware verifying the submitted token matches the one in the session. The CSRF cookie is named csrftoken by default and is configurable via CSRF_COOKIE_NAME, with CSRF_COOKIE_HTTPONLY controlling JavaScript access. XSS protection is automatic through template escaping, and SQL injection is prevented via parameterized ORM queries. The SECURE_BROWSER_XSS_FILTER setting emits the X-XSS-Protection header, SECURE_HSTS_SECONDS enables HTTP Strict Transport Security, and SECURE_CONTENT_TYPE_NOSNIFF prevents MIME-sniffing. Passwords are hashed using PBKDF2 with a per-user salt, and SECRET_KEY is used for signing cookies and tokens, which should be loaded from an environment variable rather than committed to version control. The DEBUG setting should be False in production to prevent leaking settings and environment variables through detailed tracebacks.

Static files such as CSS, JavaScript, and images are configured in settings.py with STATIC_URL, STATICFILES_DIRS, and STATIC_ROOT. The {% load static %} template tag and {% static 'path/to/file' %} tag are used to reference static files in templates, and python manage.py collectstatic gathers all static files into STATIC_ROOT for production deployment. Media files for user uploads are configured with MEDIA_URL and MEDIA_ROOT, with FileField and ImageField used in models to handle file storage. During development, media files can be served by adding a static() URL helper to urlpatterns. The ALLOWED_HOSTS setting restricts which Host headers Django accepts, returning an HTTP 400 for unrecognized hosts and preventing HTTP Host header attacks.

All chapters
  1. 1Django Fundamentals and Project Layout
  2. 2Models, ORM, and Migrations
  3. 3Advanced Querying and Optimization
  4. 4Views, URLs, and Responses
  5. 5Templates and the Presentation Layer
  6. 6Forms, Admin, and Authentication
  7. 7Middleware, Security, and File Handling
  8. 8DRF, Signals, Testing, and More

Drill it

Reading is not remembering. These come from the Django Framework deck:

Q

What is Django?

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the MTV (Model-Template-View) architectura...

Q

What is the Django MTV pattern?

MTV stands for Model-Template-View:Model – defines data structure and database schemaTemplate – handles the presentation layer (HTML)View – contains business lo...

Q

How do you create a new Django project?

Use the command:django-admin startproject myprojectThis generates the project directory with settings.py, urls.py, wsgi.py, asgi.py, and manage.py.

Q

How do you create a new Django app?

Run:python manage.py startapp myappThen add 'myapp' to the INSTALLED_APPS list in settings.py to register it with the project.