python - Django 1.3 或更低版本的 Django Admin 中的自定义过滤器

标签 python django django-admin

如何向 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??

最佳答案

感谢 gpilotino 将我推向正确的方向以实现这一目标。

我注意到问题的代码使用日期时间来确定它的实时时间。所以我使用了 DateFieldFilterSpec 并将其子类化。

from django.db import models
from django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec,DateFieldFilterSpec
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext as _
from datetime import datetime

class IsLiveFilterSpec(DateFieldFilterSpec):
    """
    Adds filtering by future and previous values in the admin
    filter sidebar. Set the is_live_filter filter in the model field attribute
    'is_live_filter'.    my_model_field.is_live_filter = True
    """

    def __init__(self, f, request, params, model, model_admin):
        super(IsLiveFilterSpec, self).__init__(f, request, params, model,
                                               model_admin)
        today = datetime.now()
        self.links = (
            (_('Any'), {}),
            (_('Yes'), {'%s__lte' % self.field.name: str(today),
                       }),
            (_('No'), {'%s__gte' % self.field.name: str(today),
                    }),

        )


    def title(self):
        return "Is Live"

# registering the filter
FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'is_live_filter', False),
                               IsLiveFilterSpec))

要使用你可以把上面的代码放到一个filters.py中,然后在你想要添加过滤器的模型中导入它

关于python - Django 1.3 或更低版本的 Django Admin 中的自定义过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7302097/

相关文章:

python - Pip 不能在 Virtual Env 内部工作,但可以在外部完美工作

python - ndarray.调整大小: passing the correct value for the refcheck argument

django - 在 10 个并发 uwsgi worker 上锁定 Django DB - 怎么做?

Django admin - 防止对象被保存,并且不显示用户确认消息

python - 预先检查 Django 管理复选框

python - 在 Azure 数据工厂上运行 .Net 和 Python 应用程序?

python - 当从遗留数据库生成模型类时,如何在 django-rest 中序列化多个模型数据

python - 如何使用 Django 中数据库的路径在网页上渲染图像?

python - 无法导入 flup.server.fcgi

django - Django在Heroku上-损坏的管理静态文件