Render template directly from Django middleware

In Django you normally specify templates to be rendered from a view class or function. Instead you can render a template directly from the Django middleware as well, as an alternative to redirecting to a different view.

For example you may want to render a maintenance template if your site is in maintenance mode. In that case you can directly call the render function that can be imported from django.shortcuts.

This example may look like the following:

from django.conf import settings
from django.shortcuts import render

class MaintenanceMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if settings.IN_MAINTENANCE:
            return render(request, 'maintenance.html)
        return self.get_response(request)

See Also

6 Non-Programming Books for Programmers