django访问自定义管理器中登录的用户

时间:2010-02-16 14:51:39

标签: django django-managers django-users

我想在我写过的自定义管理器中访问当前登录的用户。我想这样做,以便我可以过滤掉结果,只显示他们有权访问的对象。

有没有这样做而没有实际传递它?类似于它在您可以执行request.user。

的视图中的工作方式

谢谢

1 个答案:

答案 0 :(得分:5)

没有传递它,我见过的最好的方法是使用中间件(在this StackOverflow question中描述,我将复制/粘贴以方便参考):

中间件:

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)

<强>管理器:

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