How to modify Django admin filter's title

iankit picture iankit · Jun 30, 2013 · Viewed 10.2k times · Source

I have a filter (one of the defaults and not custom)

Is it possible just to change the title of filter, without write a full new custom filter ?

Because the only customization I need from the filter is its title. THere should be a way to do that without rewriting the whole filter and lookups.

Answer

lanzz picture lanzz · Jan 20, 2014

You will need to have a custom filter class, but you can actually implement a custom filter class factory that you can use everywhere you just need a filter with a custom title:

from django.contrib import admin

def custom_titled_filter(title):
    class Wrapper(admin.FieldListFilter):
        def __new__(cls, *args, **kwargs):
            instance = admin.FieldListFilter.create(*args, **kwargs)
            instance.title = title
            return instance
    return Wrapper

After that in your ModelAdmin class:

list_filter = (
    ('fieldname', custom_titled_filter('My Custom Title')),
    'plain_field',
    ...
)

(Note how the custom filter is not just a field name, but a tuple of (field_name, CustomFilterClass), you're just getting your CustomFilterClass from your custom_titled_filter() factory)