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

 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. FieldLevelPermissionsAdmin by buriy 5 years, 8 months ago
  2. DRY custom ModelAdmin.list_display methods with a decorator by exogen 4 years, 8 months ago
  3. Filter by taggit tags in the admin (Django 1.4) by albertorcf 8 months, 3 weeks ago
  4. ExtendibleModelAdminMixin by dokterbob 3 years, 6 months ago
  5. Admin Download as CSV File by msaron 1 year, 3 months ago

Comments

(Forgotten your password?)