5 Middleware is a framework of hooks into Django's request/response processing.
6 It's a light, low-level "plugin" system for globally altering Django's input
9 Each middleware component is responsible for doing some specific function. For
10 example, Django includes a middleware component, ``XViewMiddleware``, that adds
11 an ``"X-View"`` HTTP header to every response to a ``HEAD`` request.
13 This document explains all middleware components that come with Django, how to
14 use them, and how to write your own middleware.
19 To activate a middleware component, add it to the ``MIDDLEWARE_CLASSES`` list
20 in your Django settings. In ``MIDDLEWARE_CLASSES``, each middleware component
21 is represented by a string: the full Python path to the middleware's class
22 name. For example, here's the default ``MIDDLEWARE_CLASSES`` created by
23 ``django-admin.py startproject``::
25 MIDDLEWARE_CLASSES = (
26 "django.middleware.common.CommonMiddleware",
27 "django.middleware.doc.XViewMiddleware",
30 Django applies middleware in the order it's defined in ``MIDDLEWARE_CLASSES``,
31 except in the case of response and exception middleware, which is applied in
34 A Django installation doesn't require any middleware -- e.g.,
35 ``MIDDLEWARE_CLASSES`` can be empty, if you'd like -- but it's strongly
36 suggested that you use ``CommonMiddleware``.
41 django.middleware.cache.CacheMiddleware
42 ---------------------------------------
44 Enables site-wide cache. If this is enabled, each Django-powered page will be
45 cached for as long as the ``CACHE_MIDDLEWARE_SECONDS`` setting defines. See
46 the `cache documentation`_.
48 .. _`cache documentation`: http://www.djangoproject.com/documentation/cache/#the-per-site-cache
50 django.middleware.common.CommonMiddleware
51 -----------------------------------------
53 Adds a few conveniences for perfectionists:
55 * Forbids access to user agents in the ``DISALLOWED_USER_AGENTS`` setting,
56 which should be a list of strings.
58 * Performs URL rewriting based on the ``APPEND_SLASH`` and ``PREPEND_WWW``
59 settings. If ``APPEND_SLASH`` is ``True``, URLs that lack a trailing
60 slash will be redirected to the same URL with a trailing slash. If
61 ``PREPEND_WWW`` is ``True``, URLs that lack a leading "www." will be
62 redirected to the same URL with a leading "www."
64 Both of these options are meant to normalize URLs. The philosophy is that
65 each URL should exist in one, and only one, place. Technically a URL
66 ``foo.com/bar`` is distinct from ``foo.com/bar/`` -- a search-engine
67 indexer would treat them as separate URLs -- so it's best practice to
70 * Handles ETags based on the ``USE_ETAGS`` setting. If ``USE_ETAGS`` is set
71 to ``True``, Django will calculate an ETag for each request by
72 MD5-hashing the page content, and it'll take care of sending
73 ``Not Modified`` responses, if appropriate.
75 django.middleware.doc.XViewMiddleware
76 -------------------------------------
78 Sends custom ``X-View`` HTTP headers to HEAD requests that come from IP
79 addresses defined in the ``INTERNAL_IPS`` setting. This is used by Django's
80 automatic documentation system.
82 django.middleware.gzip.GZipMiddleware
83 -------------------------------------
85 Compresses content for browsers that understand gzip compression (all modern
88 django.middleware.http.ConditionalGetMiddleware
89 -----------------------------------------------
91 Handles conditional GET operations. If the response has a ``ETag`` or
92 ``Last-Modified`` header, and the request has ``If-None-Match`` or
93 ``If-Modified-Since``, the response is replaced by an HttpNotModified.
95 Also removes the content from any response to a HEAD request and sets the
96 ``Date`` and ``Content-Length`` response-headers.
98 django.middleware.sessions.SessionMiddleware
99 --------------------------------------------
101 Enables session support. See the `session documentation`_.
103 .. _`session documentation`: http://www.djangoproject.com/documentation/sessions/
105 Writing your own middleware
106 ===========================
108 Writing your own middleware is easy. Each middleware component is a single
109 Python class that defines one or more of the following methods:
114 Interface: ``process_request(self, request)``
116 ``request`` is an ``HttpRequest`` object. This method is called on each
117 request, before Django decides which view to execute.
119 ``process_request()`` should return either ``None`` or an ``HttpResponse``
120 object. If it returns ``None``, Django will continue processing this request,
121 executing any other middleware and, then, the appropriate view. If it returns
122 an ``HttpResponse`` object, Django won't bother calling ANY other middleware or
123 the appropriate view; it'll return that ``HttpResponse``.
128 Interface: ``process_view(self, request, view_func, view_args, view_kwargs)``
130 ``request`` is an ``HttpRequest`` object. ``view_func`` is the Python function
131 that Django is about to use. (It's the actual function object, not the name of
132 the function as a string.) ``view_args`` is a list of positional arguments that
133 will be passed to the view, and ``view_kwargs`` is a dictionary of keyword
134 arguments that will be passed to the view. Neither ``view_args`` nor
135 ``view_kwargs`` include the first view argument (``request``).
137 ``process_view()`` is called just before Django calls the view. It should
138 return either ``None`` or an ``HttpResponse`` object. If it returns ``None``,
139 Django will continue processing this request, executing any other
140 ``process_view()`` middleware and, then, the appropriate view. If it returns an
141 ``HttpResponse`` object, Django won't bother calling ANY other middleware or
142 the appropriate view; it'll return that ``HttpResponse``.
147 Interface: ``process_response(self, request, response)``
149 ``request`` is an ``HttpRequest`` object. ``response`` is the ``HttpResponse``
150 object returned by a Django view.
152 ``process_response()`` should return an ``HttpResponse`` object. It could alter
153 the given ``response``, or it could create and return a brand-new
159 Interface: ``process_exception(self, request, exception)``
161 ``request`` is an ``HttpRequest`` object. ``exception`` is an ``Exception``
162 object raised by the view function.
164 Django calls ``process_exception()`` when a view raises an exception.
165 ``process_exception()`` should return either ``None`` or an ``HttpResponse``
166 object. If it returns an ``HttpResponse`` object, the response will be returned
167 to the browser. Otherwise, default exception handling kicks in.
172 * Middleware classes don't have to subclass anything.
174 * The middleware class can live anywhere on your Python path. All Django
175 cares about is that the ``MIDDLEWARE_CLASSES`` setting includes the path
178 * Feel free to look at Django's available middleware for examples. The
179 default Django middleware classes are in ``django/middleware/`` in the
182 * If you write a middleware component that you think would be useful to
183 other people, contribute to the community! Let us know, and we'll
184 consider adding it to Django.