Django Intermediate Key and Context Processor

Posted by Satabi2 on Wed, 04 Sep 2019 14:48:06 +0200

Middleware and Context Processor

Django Middleware

It is a lightweight, low-level "plug-in" system that can intervene in Django's request and response processing and modify Django's input or output.

Activating Middleware

It needs to be added to the MIDDLEWARE_CLASSES tuple in the Django configuration file.

Custom Middleware

Each middleware component is a separate Python class that defines one or more of the following methods

  • _ init_: Without any parameters, the server is called once in response to the first request to determine whether the current middleware is enabled
  • process_request(request): Called before the view is executed, on each request, returning a None or HttpResponse object
  • process_view(request, view_func, view_args, view_kwargs): Called before the view is called, on each request, returns a None or HttpResponse object
  • process_template_response(request, response): Called just after the view has been executed, on each request, returns the response object that implements the render method.
  • process_response(request, response): All responses are called before they are returned to the browser, on each request, and back to the HttpResponse object.
  • process_exception(request,response,exception): Called when the view throws an exception, on each request, returns an HttpResponse object
Example:

Create mymiddleware.py file in the same directory as settings.py, define class MyException, and implement custom exception process_exception method

#---------mymiddleware.py------------

from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin

# The first way
class MyException(MiddlewareMixin):
    def process_exception(self,request,exception):
        return HttpResponse(exception)
        
# The second way
from ts22.models import UserModel
class UserMiddleware(MiddlewareMixin):
    def __init(self,get_response):
        self.get_response = get_response

    def __call__(self,request):
    	# Code executed before request arrives at view
        username = request.session.get('username','Not logged in')
        user = UserModel.objects.filter(username=username).first()
        if user and not hasattr(request,'myuser'):
            setattr(request,'myuser',user)
        response = self.get_response(request)
        # Code executed before response reaches the user's browser
        return response

Register class MyException into settings.py Middleware

#---------setting.py------------

MIDDLEWARE_CLASSES = (
      ...
    'test11.mymiddleware.MyException',
    'test11.myMiddleware.UserMiddleware',
)

# Note test11 is the project name.

Template context processor

In settings.py, the context processor currently in use is included. His function is to provide each response with the parameters it wants to add.

The role of context processors used in settings.py-> TEMPLATES-> OPTIONS-> context_processors:

django.template.context_processors.debug: Add a debug variable.
django.template.context_processors.request: Add a variable for request.
django.contrib.auth.context_processors.auth: Added a user variable.
django.contrib.messages.context_processors.messages: A message variable is added.
Custom Context Processor:

Middleware is a bit like adding attributes to request s, while context processors are a bit like adding attributes to templates. One is up, the other is down.

Create a mycontextprocessor.py file in the same directory as settings.py and define a myuser function

#-------------mycontextprocessor.py------------
def myuser(request):
    username = request.session.get('username', 'Not logged in')
    user = UserModel.objects.filter(username=username).first()
    if user:
        return {'myuser': username}
    else:
        return {}
        
# Note: 1. request must be passed in as a parameter 2. A dictionary must be returned.

Place our defined context processor in settings. py - > TEMPLATES - > OPTIONS - > context_processors.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'test11.mycontextprocessor.myuser',
            ],
        },
    },
]

Topics: Django Session Python