Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically specify the "list_display" attribute of a django ModelAdmin class?

In trying to dynamically change the columns that are displayed in the model-list page of the django admin, I tried overriding the __init__() method of my ModelAdmin class to dynamically add or remove a particular field from the list_display attribute, depending on the permissions of the current user. However, I found that ModelAdmin classes are only instantiated once per restart, so that doesn't work...

Is there another way to dynamically change the list_display field?

like image 693
Troy Avatar asked Apr 20 '13 00:04

Troy


1 Answers

While asking this question, I stumbled across the answer, so I thought I'd share...

Ticket #14206 indicates that this feature was added to django some time ago (version 1.4, I belive). ModelAdmin classes now support a get_list_display() method:

def get_list_display(self, request):
    if request.user.has_perm('my_app.my_permission'):
        list_display = ('field_1', 'field_2', 'dynamic_field',)
    else:
        list_display = ('field_1', 'field_2',)
    return list_display
like image 65
Troy Avatar answered Oct 04 '22 17:10

Troy