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

发布于 2024-08-21 06:56:41 字数 142 浏览 2 评论 0原文

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

无论如何,是否可以在不实际传递它的情况下执行此操作?类似于它在视图中的工作方式,您可以在其中执行 request.user。

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

后知后觉 2024-08-28 06:56:42

如果不传递它,我见过的最好的方法是使用中间件(在 这个 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)

经理:

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

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())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文