Callable short_description (or other Meaningful Method Attributes)

 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 5 years, 11 months ago
  2. Generic CSV export admin action factory with relationship spanning fields and labels by blackrobot 1 year, 4 months ago
  3. Allow foreign key attributes in list_display with '__' - Django 1.5 by kpacn 6 months, 2 weeks ago
  4. improved getattr template filter by luckystarr 6 years, 7 months ago
  5. Callable object as signal receiver by diverman 5 years ago

Comments

malinich (on December 6, 2013):

it not work for me

#

(Forgotten your password?)