Sometimes, you will need to get the current authenticated user in models, or other parts of your app.
To achieve this, you must create this middleware and add it to MIDDLEWARE_CLASSES in project settings:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
try: from threading import local, current_thread except ImportError: from django.utils._threading_local import local _thread_locals = local() class GlobalUserMiddleware(object): """ Sets the current authenticated user in threading locals Usage example: from app_name.middleware import get_current_user user = get_current_user() """ def process_request(self, request): setattr( _thread_locals, 'user_{0}'.format(current_thread().name), request.user) def process_response(self, request, response): key = 'user_{0}'.format(current_thread().name) if not hasattr(_thread_locals, key): return response delattr(_thread_locals, key) return response def get_current_user(): return getattr( _thread_locals, 'user_{0}'.format(current_thread().name), None) |
Usage example:
1 2 3 4 5 |
from myapp.middleware import get_current_user user = get_current_user() |