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

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.

좋은 웹페이지 즐겨찾기