I want to get the currently logged in user (request.user) in the save method of models.py. I want to check the role of the user and see if it can p
The solution proposed by @nKn is good starting point, but when I tried to implemented today, I faced two issues:
Here is my updated middleware code, which works with Django 1.10 and doesn't break unittests:
from threading import current_thread
from django.utils.deprecation import MiddlewareMixin
_requests = {}
def current_request():
return _requests.get(current_thread().ident, None)
class RequestMiddleware(MiddlewareMixin):
def process_request(self, request):
_requests[current_thread().ident] = request
def process_response(self, request, response):
# when response is ready, request should be flushed
_requests.pop(current_thread().ident, None)
return response
def process_exception(self, request, exception):
# if an exception has happened, request should be flushed too
_requests.pop(current_thread().ident, None)