Login

Callable short_description (or other Meaningful Method Attributes)

Author:
eternicode
Posted:
May 26, 2011
Language:
Python
Version:
1.3
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

malinich (on December 6, 2013):

it not work for me

#

Please login first before commenting.