Issue with django-crispy-forms and django-filter: CSS class not applying to custom ChoiceFilter field
I'm using django-filter
and django-crispy-forms
to create a filter form in Django, but I'm having trouble applying a CSS class to a custom ChoiceFilter
field. The CSS class is successfully applied to the date field but does not work for the transaction_type
field, which is defined as a ChoiceFilter
.
Here’s my current code:
import django_filters
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field
from .models import Transaction
class TransactionFilter(django_filters.FilterSet):
type = django_filters.ChoiceFilter(
choices=Transaction.TRANSACTION_TYPE_CHOICES,
field_name="type",
lookup_expr="iexact",
empty_label="Any",
)
class Meta:
model = Transaction
fields = ['transaction_type', 'date']
def __init__(self, *args, **kwargs):
super(TransactionFilter, self).__init__(*args, **kwargs)
self.form.helper = FormHelper()
self.form.helper.form_method = 'GET'
self.form.helper.layout = Layout(
Field('transaction_type', css_class='MY-CLASS'),
Field('date', css_class='MY-CLASS'),
)
In this setup, I expected both fields to have the MY-CLASS
CSS class, but only the date field reflects it, not transaction_type. I suspect this might be due to transaction_type being a custom ChoiceFilter
field, but I'm not sure how to resolve it.
I've tried a few different approaches, such as updating widget attributes and applying CSS directly through attrs, but nothing has worked so far.
Has anyone encountered this issue before or have suggestions on how to force the CSS class to apply to the ChoiceFilter
field?
Hope this helps.
ex:
import django_filters
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field
from django import forms
from .models import Transaction
class TransactionFilter(django_filters.FilterSet):
transaction_type = django_filters.ChoiceFilter(
choices=Transaction.TRANSACTION_TYPE_CHOICES,
field_name="type",
lookup_expr="iexact",
empty_label="Any",
widget=forms.Select(attrs={'class': 'MY-CLASS'}),
)
date = django_filters.DateFilter(
field_name='date',
lookup_expr='exact',
widget=forms.DateInput(attrs={'class': 'MY-CLASS'}),
)
class Meta:
model = Transaction
fields = ['transaction_type', 'date']
def __init__(self, *args, **kwargs):
super(TransactionFilter, self).__init__(*args, **kwargs)
self.form.helper = FormHelper()
self.form.helper.form_method = 'GET'
self.form.helper.layout = Layout(
Field('transaction_type', css_class='MY-CLASS'),
Field('date', css_class='MY-CLASS'),
)