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. Allow foreign key attributes in list_display with '__' by jcushman 3 months, 2 weeks ago
  2. FieldsetForm by Ciantic 6 years, 1 month ago
  3. Add URL Segments to Templates by epicserve 4 years, 7 months ago
  4. FixedCharField and related by andresj 4 years, 6 months ago
  5. [middleware] Rewrite anchors to point into Coral CDN by crime_minister 4 years, 9 months ago

Comments

(Forgotten your password?)