[Django]-Django access logged in user in custom manager

6👍

Without passing it in, the best way I’ve seen is to use a middleware (described in this StackOverflow question, I’ll copy/paste for ease of reference):

Middleware:

try:
    from threading import local
except ImportError:
    from django.utils._threading_local import local

_thread_locals = local()

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

class ThreadLocals(object):
    def process_request(self, request):
        _thread_locals.user = getattr(request, 'user', None)

Manager:

class UserContactManager(models.Manager):
    def get_query_set(self):
        return super(UserContactManager, self).get_query_set().filter(creator=get_current_user())

Leave a comment