Skip to content

Instantly share code, notes, and snippets.

@jmasonherr
Created June 28, 2018 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jmasonherr/2449ea65218b2b0d9e03b04e98bfb06b to your computer and use it in GitHub Desktop.
Save jmasonherr/2449ea65218b2b0d9e03b04e98bfb06b to your computer and use it in GitHub Desktop.
Get current user from anywhere in Django 2.x with middleware
from __future__ import absolute_import, division, print_function
try:
from threading import local
except ImportError:
from django.utils._threading_local import local
_thread_locals = local()
def get_current_request():
""" returns the request object for this thread """
return getattr(_thread_locals, "request", None)
def get_current_user():
""" returns the current user, if exist, otherwise returns None """
request = get_current_request()
if request:
return getattr(request, "user", None)
def thread_local_middleware(get_response):
# One-time configuration and initialization.
def middleware(request):
# Code to be executed for each request before
# the view (and later middleware) are called.
_thread_locals.request = request
response = get_response(request)
# Code to be executed for each request/response after
# the view is called.
if hasattr(_thread_locals, "request"):
del _thread_locals.request
return response
return middleware
@juanjcardona13
Copy link

Hi, excuseme
How should I register this middleware?

@nabazm
Copy link

nabazm commented Jan 16, 2021

Hi, excuseme
How should I register this middleware?

add this to settings.MIDDLEWARE : thread_local_middleware
MIDDLEWARE =['path_to_.thread_local_middleware']

@juanjcardona13
Copy link

Thanks!

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