Skip to content Skip to sidebar Skip to footer

Django Choicefield Filter In Admin Panel

by default django admin's list_filter provide all filters available in model choices. but apart from those I want one more filter, lets say it 'None' filter. class Mymodel: cha

Solution 1:

You don't have to make your custom list filter. Just use django's AllValuesFieldListFilter

from django.contrib.admin.filters import AllValuesFieldListFilter
...
list_filter = [..., ('choice_field', AllValuesFieldListFilter)]
...

Solution 2:

By default the admin.AllValuesFieldListFilter return a value of a choice, not verbose name of the choice. So, for resolve it use the modified admin.AllValuesFieldListFilter.

classAllValuesChoicesFieldListFilter(admin.AllValuesFieldListFilter):

    defchoices(self, changelist):
        yield {
            'selected': self.lookup_val isNoneand self.lookup_val_isnull isNone,
            'query_string': changelist.get_query_string({}, [self.lookup_kwarg, self.lookup_kwarg_isnull]),
            'display': _('All'),
        }
        include_none = False# all choices for this field
        choices = dict(self.field.choices)

        for val in self.lookup_choices:
            if val isNone:
                include_none = Truecontinue
            val = smart_text(val)
            yield {
                'selected': self.lookup_val == val,
                'query_string': changelist.get_query_string({
                    self.lookup_kwarg: val,
                }, [self.lookup_kwarg_isnull]),

                # instead code, display title'display': choices[val],
            }
        if include_none:
            yield {
                'selected': bool(self.lookup_val_isnull),
                'query_string': changelist.get_query_string({
                    self.lookup_kwarg_isnull: 'True',
                }, [self.lookup_kwarg]),
                'display': self.empty_value_display,
            }

Usage:

list_filter = (
        ('country_origin', AllValuesChoicesFieldListFilter),
    )

Post a Comment for "Django Choicefield Filter In Admin Panel"