You implement a view preprocessor by defining a process_view(self, request, view, args, kwargs) function in the middleware class. The process_view() function is called after the URL has been resolved to determine which view function and arguments to run, but before the view function is called.
The process_view() function is passed the HttpRequest object, view function, positional arguments, and keyword arguments. Any changes you make to the HttpRequest object also are passed down to the view function. The process_view() function is an excellent way to make modifications globally to define specific arguments to all view functions.
The process_view() function can also return either None or an HttpResponse object. If None is returned, Django continues processing the request and calls the view function. However, if you return an HttpResponse object, the request immediately returns that response.
Watch Out!
No other middleware applications or view functions will run if an HttpResponse is returned.
The following code snippet sets the Logging argument to True for all view functions' proxies:
class ViewLogging(object): def process_view(self, request, view, args, kwargs): try: kwargs['Logging'] = True except KeyError: pass return None
Try It Yourself: Create and Install a View Preprocessor Middleware ApplicationIn this section, you will create and install a view preprocessor application called CustomViewLogger that logs information about view functions before they are run. You will define a new ViewEvent model in the Log application to store information about view functions that are called. You will also create a template that the view_log() view function will use to render the ViewEvent objects: Follow these steps to implement a view preprocessor middleware application:
Listing 19.5. The ViewEvent Definition of the iFriends/Log/models.py File
Listing 19.6. The Imports and CustomViewLogger Definition of the django/middleware/custom.py File
Listing 19.7. Full Contents of the iFriends/templates/Custom/view_view_log.py File
Listing 19.8. The view_log() View Function of the iFriends/Custom/views.py File
|