Custom filter title in django admin

In django admin, when we add filters using list_filter(), the filter title will be the fieldName we used to filter the records. Let’s understand this with an example. Have a look at list_filter() in the code below.

@admin.register(Users)
class UsersAdmin(admin.ModelAdmin):
   list_display = ['name, 'is_active']

   list_filter = (
       'is_active',
   )

   class Meta:
       model = Users

 In the above code, fieldName is_active is used to filter the users by their active status. So filter will be looks like:

default-title

Now if you want to change the filter title “By is active” to another custom title, you can do this in this way. Just add following code in admin.py file.

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

And use customTitledFilter() in your list_filter as shown below:

list_filter = (
       ('is_active', customTitledFilter('Active Status')),
   )

custom-title

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top
Shares