开发者

Displaying dates nicely in Django's admin interface

With methods on your model that return boolean values, you can mark them as boolean so the admin's list displays show the pretty icons, like this example from the docs:

class开发者_如何学JAVA Person(models.Model):
    birthday = models.DateField()

    def born_in_fifties(self):
        return self.birthday.strftime('%Y')[:3] == '195'
    born_in_fifties.boolean = True

If a model has a DateTimeField, then it gets nicely formatted in the list displays.

However, if I've got a method on a model which returns a datetime, it shows up in list displays with yyyy-mm-dd values (e.g. 2010-03-16), which isn't very nice to read.

Is there some built-in way to mark a method as returning a datetime, similar to what exists for methods which return booleans?


Well, can't you just use:

from django.utils.dateformat import *
class Person(models.Model):
    birthday = models.DateField()
    ...

    def format_birthday(self):
        return format(self.birthday, "D d M Y")

For what it is worth: untested. Did it from memory...


PS. If you want to add some HTML in there, all you need to do is something like:

def format_birthday(self):
    return "<b>%s</b>" % format(self.birthday, "D d M Y")
format_birthday.allow_tags = True
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜