kayode-adechinan
11/6/2018 - 11:56 AM

DJANGO - Admin custom list filter

DJANGO - Admin custom list filter

class CategoryListFilter(SimpleListFilter):

    # USAGE
    # In your admin class, pass trhe filter class as tuple for the list_filter attribute:
    #
    # list_filter = (CategoryListFilter,)


    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('categories')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'category'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        list_tuple = []
        for category in Category.objects.get_published_original():
            #print category
            list_tuple.append((category.id, category.translated().title))
        return list_tuple

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        # Compare the requested value (either '80s' or 'other')
        # to decide how to filter the queryset.
        if self.value():
            return queryset.filter(category__id=self.value())
        else:
            return queryset