Middleware Installation

If you’ve read this book straight through, you’ve already seen a number of examples of middleware installation; many of the examples in previous chapters have required certain middleware. For completeness, here’s how to install middleware.

To activate a middleware component, add it to the MIDDLEWARE_CLASSES list in your Django settings. In MIDDLEWARE_CLASSES, each middleware component is represented by a string: the full Python path to the middleware’s class name. For example, here’s the default value created by django-admin startproject:

MIDDLEWARE_CLASSES = [
‘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’,
]

A Django installation doesn’t require any middleware – MIDDLEWARE_CLASSES can be empty, if you’d like – but it’s strongly suggested that you at least use CommonMiddleware.

The order in MIDDLEWARE_CLASSES matters because a middleware can depend on other middleware. For instance, AuthenticationMiddleware stores the authenticated user in the session; therefore, it must run after SessionMiddleware.

Back to Tutorial

What’s Middleware?
Installation of APR

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?