Published in 09:28 of 01/10/2013 by

Published in 09:28 of 01/10/2013

←Home

Add a counter on Django admin home page

Recently I tried many ways to add a simple record counter on Django admin home page, I needed it to look like this:

counter

I have tried django admin tools, overwriting the _meta on admin.py but the probleam with admin tools is that it installed a lot of aditional stuff I did not like to use, and the problem with other approaches was because I needed it to be dynamic. Overwriting the __meta seemed to be the right way but is binded only one time, and no updates done until the app restarts.

My friend Fernando Macedo did it the right way!

specialize the string type to add your desired dynamic behavior

from django.db import models

class VerboseName(str):
    def __init__(self, func):
        self.func = func

    def decode(self, encoding, erros):
        return self.func().decode(encoding, erros)

class UsedCoupons(models.Model):
    name = models.CharField(max_length=10)

    class Meta:
        verbose_name_plural = VerboseName(lambda: u"Used Coupons (%d)" % UsedCoupons.objects.count())

And this gives us a lesson, try to solve your problems in pure Python before looking for tricks or ready solutions. (wow it is a dynamic language!)

  • xmltodict: makes working with XML feel like you are working with JSON in django · 22:50 of 08/21/2013
  • KISS: Use the built in sum() instead of reduce to aggregate over a list comprehension in django · 20:31 of 01/11/2013
  • Django ListField e SeparetedValuesField in django · 14:01 of 01/11/2013

  • comments powered by Disqus Go Top