views:

182

answers:

1

Hi, I want to access the currently logged in user in a custom manager I have wrote. I want to do this so that I can filter down results to only show objects they have access to.

Is there anyway of doing this without actually passing it in? Something similar to how it works in views where you can do request.user.

Thanks

A: 

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())
Jack M.