DRY custom ModelAdmin.list_display methods with a decorator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def add(list_, short_description=None, position=None, **kwargs):
    """
    A helper to add a method to `list_` (usually `ModelAdmin.list_display`),
    where the method's name is added, and items may have attributes like
    `short_description` and `boolean`.
    
    `position` is the index at which to insert the item. By default, items
    are appended.
    
    Example:
    
    class ExampleAdmin(admin.ModelAdmin):
        list_display = ['__str__']
        
        @add(list_display, "in progress?", boolean=True)
        def in_progress(self, object):
            return not object.is_complete
    
        @add(list_display, mark_safe('✓'), 0, allow_tags=True)
        def checkbox(self, object):
            return '<input type="checkbox" value="%s"/>' % object.pk
    
    """
    if short_description is not None:
        kwargs['short_description'] = short_description
    def decorate(f):
        if isinstance(f, basestring):
            list_.append(f)
        else:
            for key, value in kwargs.iteritems():
                setattr(f, key, value)
            if position is None:
                list_.append(f.__name__)
            else:
                list_.insert(position, f.__name__)
            return f
    return decorate

More like this

  1. Dynamically insert or append a value to an admin option, e.g. list_display or list_filter by frankban 2 years, 8 months ago
  2. Bitwise operator queryset filter by hgeerts@osso.nl 3 years, 11 months ago
  3. FieldLevelPermissionsAdmin by buriy 6 years, 7 months ago
  4. True links in the admin list by svetlyak 6 years, 7 months ago
  5. decorators for creating paramaterized decorators and easy monkeypatching by fish2000 4 years, 3 months ago

Comments

(Forgotten your password?)