View method middleware
In most circumstances, data in requests & responses is added, removed or updated in a piecemeal fashion in view methods. However, sometimes it's convenient to apply these changes on all requests and responses.
For example, if you want to access certain data on all view methods, it's easier to use a middleware class to make this data accessible across all requests. Just as if you want to enforce a security check on all responses, it's easier to do so globally with a middleware class.
Since middleware is a rather abstract concept, before I describe the structure of a Django middleware class, I'll walk you through the various built-in Django middleware classes so you can get a firmer understanding of where middleware is good design choice.
Built-in middleware classes
Django comes equipped with a
series of middleware classes, some of which are enabled by default
on all Django projects. If you open a Django project's
settings.py
file you'll notice the
MIDDLEWARE
variable whose default contents are shown
in listing 2-29.
Listing 2-29 Default Django middleware classes in MIDDLEWARE
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
As you can see in listing 2-29,
Django projects in their out-of-the-box state come enabled with
seven middleware classes, so all requests and responses are set to
run through these seven classes. If you plan to leverage Django's
main features, I advise you not to remove any of these default
middleware classes. However, you can leave the
MIDDLEWARE
variable empty if you wish, just be aware
doing so may break certain Django functionalities.
To give you a better understanding of what the Django middleware classes in listing 2-29 do and help you make a more informed decision to disable them or not, table 2-7 describes the functionality for each of these middleware classes.
The remaining content for Django 4.0 is only available with a subscription.