iankit
iankit

Reputation: 9342

How to modify Django admin filter's title

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.

Upvotes: 56

Views: 18211

Answers (3)

A slightly more universal option:

from django.contrib.admin import SimpleListFilter

def custom_title_filter_factory(*args: Any, **kwargs: Any):
    filter_cls = kwargs.pop("filter_cls", SimpleListFilter)
    title = kwargs.pop("title", False)

    class NewFilter(filter_cls):
        def __new__(cls, *args, **kwargs):
            instance = filter_cls(*args, **kwargs)
            instance.title = title
            return instance

    return NewFilter

Upvotes: 0

lanzz
lanzz

Reputation: 43158

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:

def custom_title_filter_factory(filter_cls, title):
    class Wrapper(filter_cls):
        def __new__(cls, *args, **kwargs):
            instance = filter_cls(*args, **kwargs)
            instance.title = title
            return instance

    return Wrapper

After that in your ModelAdmin class:

from django.contrib import admin

list_filter = (
    ('fieldname', custom_title_filter_factory(admin.RelatedFieldListFilter, '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)

Upvotes: 104

Yogesh dwivedi Geitpl
Yogesh dwivedi Geitpl

Reputation: 4462

if you define labels on your fields in your model, you should see the change on filter options: Like,

is_staff = models.BooleanField(verbose_name="My Best Staff's", default=False)

Here "My Best Staff's" is filter Label.

Upvotes: 71

Related Questions