Django middleware that keep request instance for every thread.
Low maintenance activity. Last release 13 months ago. Weaker on commit activity and recent releases.
pip install django-middleware-global-requestdjango-middleware-global-request
Django middleware that keep request instance for every thread.
Install
pip install django-middleware-global-request
Note
- It's NOT good to use global request, you should pass the request instance from view to anywhere you want to use it.
- If you use the global request in Model layout, it means when you call the Model method from Django Shell, you get a None request.
Usage
-
Add django application
django_middleware_global_requestto INSTALLED_APPS inpro/settings.py:INSTALLED_APPS = [ ... 'django_middleware_global_request', ... ] -
Add
GlobalRequestMiddlewareto MIDDLEWARE inpro/settings.py:MIDDLEWARE = [ ... 'django_middleware_global_request.middleware.GlobalRequestMiddleware', ... ] -
Use
get_requestto get the global request instance from a function inpro/models.py:from django.db import models from django.conf import settings from django_middleware_global_request import get_request class Book(models.Model): name = models.CharField(max_length=64) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.author: request = get_request() if request: self.author = request.user return super().save(*args, **kwargs) -
Use
with GlobalRequest(xxx): passto set the global request to a new value in NON-USER-REQUEST context, e.g. inmanagement commandcontext or inpython manage.py shellcontext. Out of thewith scope, the global request instance will be reset to the value when entering into thewith scope.import djclick as click from django.contrib.auth import get_user_model from django_middleware_global_request_example.models import Book from django_middleware_global_request import GlobalRequest @click.command() @click.option("-n", "--number", type=int, default=10) def create(number): admin = get_user_model().objects.all()[0] with GlobalRequest(user=admin): for i in range(number): book = Book(name="book{idx}".format(idx=i+1)) book.save() print(i, book.name, book.author.username)