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

萝らか妹 提交于 2021-01-29 21:32:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!