Part IV: Implementing Advanced Website Components
| HOUR 20 Internationalization and Localization |
|
| HOUR 22 Implementing Multiple Websites |
|
Hour 19. Implementing Middleware
What You'll Learn in This Hour |
|
So far, all the code that we have written to manipulate views has been in the view functions and templates. Django provides a simple-to-use framework, called middleware, that allows you to manipulate the behavior of views at the request and response level.
Using the middleware framework, you can write your own custom functions that hook into the request and response engine. These custom functions can be used to log information about the request or response, alter the request or response, or perform any number of other operations.
Django itself implements middleware for several things such as providing request.session and request.user information to the view functions. Several other middleware applications can be installed into Django.
This hour discusses how to install middleware applications and how to build your own custom middleware applications. You'll also learn about some of the middleware applications that are built into Django.
Installing Middleware
You install middleware applications using the MIDDLEWARE_CLASSES setting in the project's settings.py file. Each line in the MIDDLEWARE_CLASSES setting is a string representing the full Python path to a class in the middleware application.
For example, the following middleware applications are automatically installed when you create a new project:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
)
To install a middleware application, make certain that it is installed somewhere in the Python path, and then add the middleware application to the MIDDLEWARE_CLASSES setting.
Did you Know?
The order in which applications appear in the MIDDLEWARE_CLASSES setting is important. Middleware is applied in the order in which it appears in the setting. For prerequest and preview hooks, the first item in the setting is applied first. For postresponse and postexception hooks, the first item in the setting is applied last.