class warehousePeopleBase(ModelAdmin): model = warehousePeople menu_label = '库房人员出入库信息' # ditch this to use verbose_name_plural from model menu_icon = 'site' # change as required list_display = ['name', 'yearMonth', 'month', 'warehouse', 'subjectMatter'] list_filter = ('name', 'yearMonth', 'month', 'warehouse',) wagtail怎么将右侧过滤器的yearMonth字段更改为日期选择器?可以任意的选择年份和月份?
时间: 2023-12-22 15:02:54 浏览: 153
Designing A Common Sense Approach to Web & Mobile Application Design
你可以使用 Django 的 DateField 和 DateHierarchyFilter 来实现这个功能。首先,你需要在模型中将 yearMonth 字段更改为 DateField 类型:
```python
class WarehousePeople(models.Model):
name = models.CharField(max_length=100)
yearMonth = models.DateField()
month = models.CharField(max_length=10)
warehouse = models.CharField(max_length=100)
subjectMatter = models.CharField(max_length=100)
def __str__(self):
return self.name
```
接下来,在 ModelAdmin 中使用 DateHierarchyFilter 和 DateFieldListFilter 类来更改过滤器:
```python
from django.contrib.admin import DateFieldListFilter, DateHierarchyFilter
class WarehousePeopleAdmin(ModelAdmin):
model = WarehousePeople
menu_label = '库房人员出入库信息'
menu_icon = 'site'
list_display = ['name', 'yearMonth', 'month', 'warehouse', 'subjectMatter']
list_filter = (
('yearMonth', DateHierarchyFilter),
('name',),
('warehouse',),
)
date_hierarchy = 'yearMonth'
date_hierarchy_drilldown_urls = {}
def changelist_view(self, request, extra_context=None):
self.date_hierarchy_drilldown_urls = {}
return super().changelist_view(request, extra_context)
def get_list_filter(self, request):
"""
Return the list of filters that should be used in the admin
list view.
"""
list_filter = super().get_list_filter(request)
for filter_spec in list_filter:
if isinstance(filter_spec, tuple):
field_name = filter_spec[0]
else:
field_name = filter_spec
try:
field = self.opts.get_field(field_name)
except FieldDoesNotExist:
continue
if isinstance(field, models.DateField):
cls = DateFieldListFilter
if field_name == 'yearMonth':
cls = lambda f, request: DateHierarchyFilter(f, request, field_name='yearMonth')
filter_spec = (filter_spec[0], cls)
if field_name == self.date_hierarchy:
self.date_hierarchy_drilldown_urls = {
'day': reverse('admin:%s_%s_day' % self.get_model_info(), args=['year', 'month', 'day']),
'month': reverse('admin:%s_%s_month' % self.get_model_info(), args=['year', 'month']),
'year': reverse('admin:%s_%s_year' % self.get_model_info(), args=['year']),
}
yield filter_spec
else:
yield filter_spec
```
这段代码中,我们将 yearMonth 字段的过滤器更改为 DateHierarchyFilter 类,这样就可以使用日期选择器来选择年份和月份了。同时,我们还需要重载 get_list_filter 和 changelist_view 方法来支持日期选择器。
阅读全文