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
Score:
1 (after 1 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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.