JerryLong
JerryLong

Reputation: 79

Django admin custom list_display

I want to custom list_display by different permissions. For example, super could see the "price", others are not. admin.py

class bookAdmin(admin.ModelAdmin):
    def display_resort(request):
         if request.user.is_super:
             resort_list = ["name", "author", "price"]
         else:
             resort_list = ["name", "author"]
         return resort_list
    list_display = ['display_resort']

But i got

display_resort() takes exactly 1 argument (2 given)

I think the return stuff are not in the right method, i had also try return "resort_list" in tuple, iteration and string, etc. But all failed. Put in simply, i want to custom the whole list_display not only one field of it. Seeking your help, Thanks.

---With freylis's help, My codes now is:

class bookAdmin(admin.ModelAdmin):
    def get_list_display(self, request):
         default_list_display = super(bookAdmin, self).get_list_display(request)
         if request.user.is_super:
             default_list_display = ["name", "author", "price"]
         else:
             default_list_display = ["name", "author"]
         return default_list_display

Here's a document of get_list_display https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_list_display, but not very detail.

Upvotes: 3

Views: 4071

Answers (1)

freylis
freylis

Reputation: 814

In first, all methods of class takes first argument self, so you need define you method like:

def display_resort(self, request):
     if request.user.is_super:
         resort_list = ["name", "author", "price"]
     else:
         resort_list = ["name", "author"]
     return resort_list

But isnt a django-way. You need define get_list_display method in your bookAdmin class:

class bookAdmin(admin.ModelAdmin):

    def get_list_display(self, request):
        default_list_display = super(bookAdmin, self).get_list_display(request)
        if request.user.is_superuser:
            # return any list
        return default_list_display

Upvotes: 5

Related Questions