Accessing request.user in models.py and signals.py

JunePyo Suh·2020년 9월 22일
0
post-custom-banner

Use a custom middleware class

from stackoverflow

from threading import local

_thread_locals = local()

def get_current_user():
    return getattr(_thread_locals, 'user', None)

class ThreadLocals( object ):
    """Middleware that gets various objects from the request object and saves them in thread local storage."""
    def process_request( self, request ):
    _thread_locals.user = getattr( request, 'user', None )

// in settings.py
MIDDLEWARE_CLASSES += (
    "your.path.to.middleware.ThreadLocals"
)

It is important that you use threading.local instead of using a dictionary with threading.current_thread, as the latter may lead to a memory leak (old values remaining in the current_thread as long as the application is running)

A library is also available for this purpose.

post-custom-banner

0개의 댓글