Login

Dynamically insert or append a value to an admin option, e.g. list_display or list_filter

Author:
frankban
Posted:
August 22, 2011
Language:
Python
Version:
1.3
Tags:
admin list_display list_filter
Score:
0 (after 0 ratings)

You can use this function to change an admin option dynamically.

For example, you can add a custom callable to list_display based on request, or if the current user has required permissions, as in the example below:

class MyAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'other_field')

    def changelist_view(self, request, extra_context=None):
        if request.user.is_superuser:
            add_dynamic_value(self, 'list_display', my_custom_callable)
        return super(MyAdmin, self).changelist_view(request, extra_context)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def add_dynamic_value(instance, attr, value, index=None, cache={}):
    """
    Dynamically insert or append (in a thread safe way) 
    a value to an admin option, e.g. *list_display* or *list_filter*.

    Arguments:
        
        - instance: an *admin.ModelAdmin* instance
        - attr: a string representing the admin option to change 
          (e.g. *list_display*)
        - value: the value to append or insert
        - index: the position where to insert the new value (None: append)
    """
    key = '%d%s' % (id(instance), attr)
    if key not in cache:
       cache[key] = getattr(instance, attr)
    new_value = list(cache[key])
    if index:
        if new_value[0] == 'action_checkbox':
            index += 1
        new_value.insert(index, value)
    else:
        new_value.append(value)
    setattr(instance, attr, new_value)

More like this

  1. ExtendibleModelAdminMixin by dokterbob 5 years, 9 months ago
  2. Filter by taggit tags in the admin (Django 1.4) by albertorcf 3 years ago
  3. DRY custom ModelAdmin.list_display methods with a decorator by exogen 6 years, 11 months ago
  4. assign fields dynamically in newforms by rubic 8 years, 6 months ago
  5. Admin action for a generic "CSV Export" by javinievas 4 years, 6 months ago

Comments

Please login first before commenting.