carltongibson / django-filter

A generic system for filtering Django QuerySets based on user selections

Home Page:https://django-filter.readthedocs.io/en/main/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

filter_overrides for BooleanField to checkbox doesn't work as expected

jdbit opened this issue · comments

commented

Hi!
I'm trying to override a boolean field app_support to checkbox. According to the documentation, I added this code to my filter:

class Meta:
   model = Product
   fields = ['app_support']
   filter_overrides = {
       models.BooleanField: {
           'filter_class': django_filters.BooleanFilter,
           'extra': lambda f: {
               'widget': forms.CheckboxInput,
           },
       },
   }

The checkbox appears in the filter form, buy when I submit the form, it shows zero results and the url query looks like ?app_support=on instead of ?app_support=True. As soon as I delete the override, it works fine. What I'm doing wrong?

commented

Fixed it after adding a method checkbox_filter:

class Meta:
   model = Product
   fields = ['app_support']
   filter_overrides = {
       models.BooleanField: {
           'filter_class': django_filters.BooleanFilter,
           'extra': lambda f: {
               'widget': forms.CheckboxInput,
               'method': 'checkbox_filter',
           },
       },
   }
def checkbox_filter(self, queryset, name, value):
        if value == True:
            return queryset.filter(**{name: value})
        else:
            return queryset