Last active
May 3, 2018 02:50
-
-
Save Sanyambansal76/c8d48385898282f7fd55bf4a4849647c to your computer and use it in GitHub Desktop.
Django Access the Request or User Object Inside the Models and Signals.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i made a new version of this: https://gist.github.com/rbtsolis/1db34b7d5a2ce9594f226cae414f9f12