Skip to content

Instantly share code, notes, and snippets.

@daltonpinheiro
Forked from rbtsolis/middleware.py
Created March 18, 2019 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daltonpinheiro/3f99f22905a27601c4db155794a33e2d to your computer and use it in GitHub Desktop.
Save daltonpinheiro/3f99f22905a27601c4db155794a33e2d to your computer and use it in GitHub Desktop.
Django Access the Request or User Object Inside the Models and Signals
# 1) Create a middlewares/middlewares.py file and copy this:
import threading
class RequestMiddleware:
def __init__(self, get_response, thread_local=threading.local()):
self.get_response = get_response
self.thread_local = thread_local
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
self.thread_local.current_request = request
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
#Include Middleware in your settings.py file
MIDDLEWARE = [
'middlewares.middlewares.RequestMiddleware',
]
# models.py or signals.py file
from middlewares.middlewares import RequestMiddleware
# First we need create an instance of that and later get the current_request assigned
request = RequestMiddleware(get_response=None)
request = request.thread_local.current_request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment