且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-01 20:10:10

没有传入,我看到的***的方法是使用中间件(在这个***问题,我将复制/粘贴以方便参考):

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

中间件

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())