问题
Django 1.11.
In admin.py I have:
class AuditAdmin(DeactivateMixin, admin.ModelAdmin):
   """all the superclass stuff"""
from which I subclass my model's stuff with various custom methods:
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 ?
So inside inline_add_somemodelattribute1 method I need to make decision based on the user but that method does not take request as an argument. How do I get my user data in this case? I did not find anything relevant  in self or my_object
Thanks
回答1:
Easiest way of access current request is using crequest. You can use it like this:
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:
回答2:
You may consider setting some values that you may require in your custom methods related to request user in changelist_view method as :
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)
来源:https://stackoverflow.com/questions/53268099/django-access-to-user-info-from-admin-py-for-methods-with-no-request-object