【问题标题】:Overide django admin ListFilter templates覆盖 django admin List_Filter 模板
【发布时间】:2015-03-16 22:46:12
【问题描述】:

我想基于此覆盖默认的 django 管理过滤器模板以使用我自己的模板:

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

我通过继承django.contrib.admin.SimpleListFilter编写了自己的SimpleListFilterclass

class PublisherStateFilter(admin.SimpleListFilter):
    title = _('Status')
    parameter_name = 'status'
    template = 'admin/blogitty/filter.html'

    [...]

这很好用。

但是,我想对所有管理员过滤器使用相同的模板。有没有办法覆盖给定应用程序的所有过滤器模板,而不必为每个 ForeignKey 和 ManyToMany 关系定义自定义 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

【问题讨论】:

    标签: django django-admin django-admin-filters cookiecutter-django


    【解决方案1】:

    这可能会有所帮助

    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 中

    【讨论】:

      猜你喜欢
      • 2017-08-23
      • 2011-06-21
      • 2020-05-21
      • 2017-01-10
      • 2023-04-03
      • 2018-04-13
      • 2019-07-02
      • 2012-03-30
      • 2012-04-06
      相关资源
      最近更新 更多