Reputation: 1186
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:
filters.py
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):
transaction_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'),
)
my view:
@login_required
def transactions_list(request):
transactions_filter = TransactionFilter(
request.GET,
Transaction.objects.filter(user=request.user),
)
context = {'filter': transactions_filter}
return render(request, 'tracker/transactions_list.html', context)
My template:
<form method="GET">
<div class="mb-2 form-control">
{% crispy filter.form %}
</div>
<button class="btn btn-success">
Filter
</button>
</form>
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?
Upvotes: 0
Views: 39
Reputation: 381
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'),
)
Upvotes: 0