django_filters filter_overrides not applying to CharFields with choices

Viewed 50

I have declared a django_filters.FilterSet with a Meta class where I would like to use filter_overrides in order to customise some of the filters. I am using code very similar to the example in the official documentation:

class AccommodationFilter(django_filters.FilterSet):

class Meta:
    model = AccommodationOffer
    fields = ['numberOfPeople', 'petsAllowed', 'typeOfResidence', 'startDateAccommodation' ]
    filter_overrides = {
            models.BooleanField: {
            'filter_class': django_filters.BooleanFilter,
            'extra': lambda f: {
                'widget': forms.CheckboxInput(attrs={'class':'form-control', 'value' : 'true'}),
            },
        },
        models.CharField: {
            'filter_class': django_filters.ChoiceFilter,
            'extra': lambda f: {
                'widget': forms.Select(attrs={'class':'form-control'}),
            },
        },
    }

The BooleanFields are showing up as expected, however no matter what I try, the CharFields (which have choices set) do not render with the class="form-control" attribute.

1 Answers

As mentioned per comment this is a bug within django_filters. As long as this issue doesn't get resolved one would have to modify the django_filters code.

In case anyone walks into the same problem this is the workaround I came up with:

class MyFilterSet(django_filters.FilterSet):

    [...]
    
    def __init__(self, data=None, queryset=None, *, request=None, prefix=None):
        super().__init__(data, queryset, request=request, prefix=prefix)
        for f in self.filters.values():
            if isinstance(f, django_filters.ChoiceFilter):
                    f.extra.update({'widget': forms.Select(attrs={'class' : 'form-control'})})
Related