Skip to content

Instantly share code, notes, and snippets.

@rbtsolis
Created May 3, 2018 02:46
Show Gist options
  • Save rbtsolis/1db34b7d5a2ce9594f226cae414f9f12 to your computer and use it in GitHub Desktop.
Save rbtsolis/1db34b7d5a2ce9594f226cae414f9f12 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
@jafrancov
Copy link

Awesome! works great, thank you.

@d-rama
Copy link

d-rama commented Dec 20, 2018

Thank you! This works perfectly!

@daltonpinheiro
Copy link

Very good, but i receved ('_thread._local' object has no attribute 'current_request').
What do i solve? Thanks.

@abdul-hamid-achik
Copy link

cool

@kalteVollmilch
Copy link

Very good, but i receved ('_thread._local' object has no attribute 'current_request').
What do i solve? Thanks.

Probably doesn't help you anymore, but in case someone else comes across this problem:
For me the problem was that I was still using MIDDLEWARE_CLASSES[] instead of MIDDLEWARE[]
So renaming that solved my problem without breaking my project

@Ambassadeur
Copy link

Ambassadeur commented Feb 3, 2020

Very good, but i receved ('_thread._local' object has no attribute 'current_request').
What do i solve? Thanks.

Hi i'm having the same error. How did we solve it ? I am using MIDDLEWARE¨tupple as suggested by @kalteVollmilch but i's not working

@AlekseiKhatkevich
Copy link

Same trouble
AttributeError: '_thread._local' object has no attribute 'current_request'
Where exaclty in a middlware i need to insert it? Is it possition dependent?

@aabishkar
Copy link

Same problem any solution?

@hossainchisty
Copy link

Awesome! works great.

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