如何扩展Django管理员的DateFieldListFilter类? [英] How do I extend Django admin's DateFieldListFilter class ?
问题描述
我是Django的新手,并且有一个带有DateTime字段的模型,该模型显示在django管理员中。
I am a newbie with Django and have a model with a DateTime field which is shown in the django admin.
在指定字段名时,在list_filter选项中获取具有4个链接(今天,本月,过去7天等)的日期字段的基本Django过滤器界面。
In the list_filter option when I specify the fieldname I get the basic Django filter interface for date fields with 4 links (today, this month, past 7 days, etc.)
我现在要添加接下来的7天 选项。这将需要通过扩展DateFieldListFilter类进行一些细微的调整。但是,Django会抛出系统检查(admin.E114) list_filter [0]的值不得继承自 FieldListFilter。当我尝试扩展它时。
I now want to add a "next 7 days" option. This will require a minor tweak by extending the DateFieldListFilter class. However, Django throws the system check (admin.E114) The value of 'list_filter[0]' must not inherit from 'FieldListFilter'. when I try to extend it.
经过一点搜索后,似乎唯一可行的方法是扩展SimpleListFilter类,但对于这么小的事情,似乎需要做很多工作。 (因为我将不得不复制DateFieldListFilter中已经处理的功能)
The only way it seems possible after a bit of search is by extending the SimpleListFilter class but it seems like a lot of work for such a small thing. (since I will have to duplicate functionality already taken care of in DateFieldListFilter)
有没有更简单的方法来实现这一点?
Is there a simpler way of achieving this?
推荐答案
假设我们有一个名为 Book
的模型,该模型的 published_at
字段,它是一个 DateTimeField
。然后,您可以通过执行以下操作来实现这种类型的过滤(代码基于DateFieldListFilter,如 https://github.com/django/django/blob/4ad2f862844d35404e4798b3227517625210a72e/django/contrib/admin/filters.py ):
Assume we have a model called Book
with a published_at
field which is a DateTimeField
. You could then achieve this type of filtering by doing something like this (code is based on DateFieldListFilter as seen in https://github.com/django/django/blob/4ad2f862844d35404e4798b3227517625210a72e/django/contrib/admin/filters.py):
import datetime
from django.contrib import admin
from django.contrib.admin.filters import DateFieldListFilter
from django.utils.translation import gettext_lazy as _
class MyDateTimeFilter(DateFieldListFilter):
def __init__(self, *args, **kwargs):
super(MyDateTimeFilter, self).__init__(*args, **kwargs)
now = timezone.now()
# When time zone support is enabled, convert "now" to the user's time
# zone so Django's definition of "Today" matches what the user expects.
if timezone.is_aware(now):
now = timezone.localtime(now)
today = now.date()
self.links += ((
(_('Next 7 days'), {
self.lookup_kwarg_since: str(today),
self.lookup_kwarg_until: str(today + datetime.timedelta(days=7)),
}),
))
class BookAdmin(admin.ModelAdmin):
list_filter = (
('published_at', MyDateTimeFilter),
)
这篇关于如何扩展Django管理员的DateFieldListFilter类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!