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

Joh*_*ohn 2 django django-managers django-users

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

有没有这样做而没有实际传递它?类似于它在您可以执行request.user的视图中的工作方式.

谢谢

Jac*_* M. 5

没有传递给它的,我见过的最好的方法是使用一个中间件(描述这个StackOverflow的问题,我会复制/粘贴为便于参考):

中间件:

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)
Run Code Online (Sandbox Code Playgroud)

经理:

class UserContactManager(models.Manager):
    def get_query_set(self):
        return super(UserContactManager, self).get_query_set().filter(creator=get_current_user())
Run Code Online (Sandbox Code Playgroud)