Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sanyambansal76/c8d48385898282f7fd55bf4a4849647c to your computer and use it in GitHub Desktop.
Save Sanyambansal76/c8d48385898282f7fd55bf4a4849647c to your computer and use it in GitHub Desktop.
Django Access the Request or User Object Inside the Models and Signals.
#Access Request Object Inside the Models and Signals
#Create a middleware.py inside any app for example :- blog
#middleware.py
import threading
class RequestMiddleware(object):
thread_local = threading.local()
def process_request(self, request):
if request.user.is_authenticated():
RequestMiddleware.thread_local.current_request = request
#Include Middleware
#settings.py
MIDDLEWARE_CLASSES = (
'blog.middleware.RequestMiddleware'
)
#models.py or signals.py
from blog.middleware import RequestMiddleware
request = RequestMiddleware.thread_local.current_request
user = request.user
@jasonhoward64
Copy link

Doesn't work

AttributeError: '_thread._local' object has no attribute 'current_request'

@zudheer
Copy link

zudheer commented Feb 28, 2018

AttributeError: '_thread._local' object has no attribute 'current_request'

@Allan-Nava
Copy link

How can I login another user with post_signal in model ?

@rbtsolis
Copy link

rbtsolis commented May 3, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment