Login

Callable short_description (or other Meaningful Method Attributes)

Author:
eternicode
Posted:
May 26, 2011
Language:
Python
Version:
1.3
Tags:
admin callables
Score:
0 (after 0 ratings)

The django admin (as of 1.3) doesn't allow for short_description (and other ModelAdmin function attributes) to be a callable. Until that happens, this handy snippet allows you to return dynamic descriptions.

Note, I haven't actually tested this yet -- but I plan to when I have the free time.

 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
38
39
from django.contrib.admin import ModelAdmin
from datetime.datetime import now

class ProfileAdmin(ModelAdmin):

    list_display = ('votes_today',)

    def votes_today(self, obj):
        today = now().replace(hour=0, minute=0, second=0, microsecond=0)
        return obj.vote_set.filter(created__gte=today)
    votes_today.short_description = lambda: 'Votes today (%s)' % now().strftime('%B %d')

# Doesn't work, callables not supported


#---------------------------------------------------------#


from django.contrib.admin import ModelAdmin
from datetime.datetime import now

class ProfileAdmin(ModelAdmin):

    list_display = ('votes_today',)

    class VotesToday:
        def __call__(self, model_admin, obj):
            today = now().replace(hour=0, minute=0, second=0, microsecond=0)
            return obj.vote_set.filter(created__gte=today)

        @property
        def short_description(self):
            return 'Votes today (%s)' % now().strftime('%B %d')

    @property
    def votes_today(self):
        if not hasattr(self, '__votes_today'):
            self.__votes_today = self.VotesToday()
        return self.__votes_today

More like this

  1. Callable Class View by zbyte64 7 years, 2 months ago
  2. Generic CSV export admin action factory with relationship spanning fields and labels by blackrobot 2 years, 7 months ago
  3. Allow foreign key attributes in list_display with '__' - Django 1.5 by kpacn 1 year, 9 months ago
  4. improved getattr template filter by luckystarr 7 years, 10 months ago
  5. Callable object as signal receiver by diverman 6 years, 4 months ago

Comments

malinich (on December 6, 2013):

it not work for me

#

Please login first before commenting.