【发布时间】:2010-11-02 18:40:30
【问题描述】:
如何向 django admin 添加自定义过滤器(显示在模型仪表板右侧的过滤器)?我知道包含基于该模型字段的过滤器很容易,但是像这样的“计算”字段呢:
class NewsItem(models.Model):
headline = models.CharField(max_length=4096, blank=False)
byline_1 = models.CharField(max_length=4096, blank=True)
dateline = models.DateTimeField(help_text=_("date/time that appears on article"))
body_copy = models.TextField(blank=False)
when_to_publish = models.DateTimeField(verbose_name="When to publish", blank=True, null=True)
# HOW CAN I HAVE "is_live" as part of the admin filter? It's a calculated state!!
def is_live(self):
if self.when_to_publish is not None:
if ( self.when_to_publish < datetime.now() ):
return """ <img alt="True" src="/media/img/admin/icon-yes.gif"/> """
else:
return """ <img alt="False" src="/media/img/admin/icon-no.gif"/> """
is_live.allow_tags = True
class NewsItemAdmin(admin.ModelAdmin):
form = NewsItemAdminForm
list_display = ('headline', 'id', 'is_live')
list_filter = ('is_live') # how can i make this work??
【问题讨论】:
-
其他人已经说过这个功能在主干(1.4 dev)中。更多信息:release note 和 documentation。
-
这里有一个更好的文档链接;扩展 SimpleListFilter 是要走的路。 FilterSpecs 已过期。 docs.djangoproject.com/en/dev/ref/contrib/admin/…
-
见下面的matley answer,带有官方文档的链接。
标签: python django django-admin