Django:对于没有请求对象的方法,从 admin.py 访问用户信息?

Django: access to user info from admin.py for methods with no request object?

Django 1.11.

admin.py 我有:

class AuditAdmin(DeactivateMixin, admin.ModelAdmin):
   """all the superclass stuff"""

我使用各种自定义方法从中继承模型的内容:

class SomeModelAdmin(AuditAdmin):
    list_display = ["filed1", "filed2", "field3"] 

    def get_queryset(self, request):
        if request.user.is_superuser: 
            #do something extra

    def inline_add_somemodelattribute1(self, my_object):
        #how to access user if I don't have request ?

所以在 inline_add_somemodelattribute1 方法中我需要根据用户做出决定,但该方法不将 request 作为参数。在这种情况下,如何获取我的 user 数据?我没有在 selfmy_object

中找到任何相关内容

谢谢

访问当前请求的最简单方法是使用 crequest。你可以这样使用它:

from crequest.middleware import CrequestMiddleware

class SomeModelAdmin(...):
     ...

     def inline_add_somemodelattribute1(self, my_object):
          crequest = CrequestMiddleware.get_request()
          # your logics here for example: if crequest.user.pk == 1:

您可以考虑在 changelist_view 方法中与请求用户相关的自定义方法中设置一些您可能需要的值:

def changelist_view(self, request, extra_context=None):
    # setting is_superuser attribute to be used in custom methods.
    setattr(self, 'is_superuser', request.user.is_superuser)

    return super().changelist_view(request, extra_context)