覆盖Django管理后台ListFilter模板

5
我希望能够覆盖默认的Django后台管理筛选器模板,使用我自己的模板,模板基于以下内容:

https://github.com/feincms/feincms/blob/master/feincms/templates/admin/filter.html

我通过继承自django.contrib.admin.SimpleListFilter编写了自己的SimpleListFilter类。请注意,不要改变HTML标签。
class PublisherStateFilter(admin.SimpleListFilter):
    title = _('Status')
    parameter_name = 'status'
    template = 'admin/blogitty/filter.html'

    [...]

这个非常完美。

下拉选择过滤器

然而,我希望对于所有管理员筛选器都使用同一模板。有没有一种方法可以覆盖给定应用程序的所有筛选器模板,而不必为每个ForeignKeyManyToMany关系定义自定义ListFilter

我的项目名为blogitty。我尝试了模板DIR的两个选项:

blogitty/templates/admin/filter.html

并且:

blogitty/templates/admin/blogitty/filter.html

很遗憾 :-(

查看源代码:

https://github.com/django/django/blob/master/django/contrib/admin/options.py#L1030

    return TemplateResponse(request, form_template or [
        "admin/%s/%s/change_form.html" % (app_label, opts.model_name),
        "admin/%s/change_form.html" % app_label,
        "admin/change_form.html"
    ], context)

https://github.com/django/django/blob/master/django/contrib/admin/options.py#L1569

    return TemplateResponse(request, self.change_list_template or [
        'admin/%s/%s/change_list.html' % (app_label, opts.model_name),
        'admin/%s/change_list.html' % app_label,
        'admin/change_list.html'
    ], context)

据我所了解,Django ModelAdmin会检查多个路径以渲染给定模型的changeform或changelist。然而,对于ListFilter,没有进行额外的检查以加载自定义模板。

https://github.com/django/django/blob/master/django/contrib/admin/filters.py#L60

class ListFilter(object):
    title = None  
    template = 'admin/filter.html'

更新-TEMPLATE_DIRS设置:
BASE_DIR = dirname(dirname(__file__))    

TEMPLATE_DIRS = (
    join(BASE_DIR, 'templates'),
)  

项目布局基于Daniel Greenfeld的cookiecutter-django

1个回答

2
这可能有所帮助。
class ClassFilter1(admin.ModelAdmin):
    title = 'Filter Class'
    parameter_name = 'filter-class'

    def lookups(self, request, model_admin):
       # Your Lookups

    def queryset(self, request, queryset):
       # Your Lookups

class FilterClass(admin.ModelAdmin):
    list_filter = (ClassFilter1, ClassFilter2)
    change_list_template = 'polls/change_list_template.html'

覆盖change_list_template.html并将.html文件放置在polls/templates/polls中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接