Django Global Request

< 1 min read

When a page is requested, Django builds an HttpRequest object containing metadata about the request. Django passes this request to the view it calls for the page request. Generally, you have access to the HttpRequest object from inside the view.

But often, it is required to have access to the HttpRequest object from within other places as well. For example, you might have a Django model where you have a logic based on the request data. One solution is to pass the request object to every method that requires to have access to the HttpRequest object. But it breaks the overall design pattern and it is not always possible to pass the request object to every other place.

What is the solution then?

Well, we can write a Django middleware that can save the request object in a global variable. We can then use that global variable where we need access to the request object.

The good news is, like many other fantastic libraries, we already have a Django package that implemented the same for us. You can install the package, add the package name in INSTALLED_APPS and middleware in the MIDDLEWARES list, and you are done.

Step 1: Install the package:

pip install django-middleware-global-request

Step 2: Add Django application django_global_request to INSTALLED_APPS in settings.py

INSTALLED_APPS = [
    ...
    'django_middleware_global_request',
    ...
]

Step 3: Add GlobalRequestMiddleware to MIDDLEWARE in settings.py

MIDDLEWARE = [
    ...
    'django_middleware_global_request.middleware.GlobalRequestMiddleware',
    ...
]

Usage: Get request instance with function get_request from django_middleware_global_request.middleware

from django_middleware_global_request.middleware import get_request

class TestModel(models.Model):

    field1 = models.CharField(max_length=32)

    def hello(self):
        request = get_request()
        ...

Source: https://pypi.org/project/django-middleware-global-request/

Hope you find it useful.

Leave a Reply

Your email address will not be published.