Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overide django admin ListFilter templates

I want to overide default django admin filter template to use my own template based on this:

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

I've written my own SimpleListFilterclass by inheriting from django.contrib.admin.SimpleListFilter

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

    [...]

This works perfectly.

Dropdown Select Filter

However I would like to use the same template for all admin filters. Is there a way to overide all filter templates for a given app, without having to define custom ListFilterfor each ForeignKey and ManyToMany relationships.

With my project as blogitty. I tried both options for template DIR:

blogitty/templates/admin/filter.html

And:

blogitty/templates/admin/blogitty/filter.html

No luck :-(

Looking through the source code:

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)

As far as I understand it. Django ModelAdmin checks multiple paths for rendering changeform or changelist for a given model. However for a ListFilter, no extra checks are done to load custom templates.

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

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

Update — TEMPLATE_DIRS settings:

BASE_DIR = dirname(dirname(__file__))    

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

Project layout is based on cookiecutter-django by Daniel Greenfeld

like image 934
mishbah Avatar asked Nov 01 '22 11:11

mishbah


1 Answers

This might help

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'

And overide the change_list_template.html and place the .html in polls/templates/polls

like image 57
Jay Dave Avatar answered Nov 09 '22 13:11

Jay Dave