Rename Filter Label Model Admin Django

769 Views Asked by At

Is it possible to change this label in the list filter from model admin without creating a custom filter? enter image description here

I'm using the same external model for 2 different fields and user needs to filter the table using both fields (separately or combining them).

Without the rename, the Admin view will have 2 filters with same name applying to different fields.(see picture) Not the best ux.

enter image description here

The first column is a field not in this model it is calling related model field as a list_display and listFilter:

list_display = ([...] 'contract_gjl_entity', 'gjl_paying_entity', [...])
list_filter = (
    [...]
    ('gjl_paying_entity__name', DropdownFilter),
    ('contract__gjl_entity__name', DropdownFilter),
    [...]


# Function that get the entities using contract id field and join them in a csv text to show in grid

def contract_gjl_entity(obj):
        contract_id = obj.contract_number
        contract = Contract.objects.get(id=contract_id)
        return ", ".join(str(seg) for seg in contract.gjl_entity.all())

What I need is to rename the 'By GJL Entity' --> 'By Contract Entity' and the other 'By GJL Entity' --> 'By Paying Entity'

1

There are 1 best solutions below

1
On BEST ANSWER
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',
    ...
)