I’m trying to build a view so that a user can filter various attributes of a primary entity and attributes of entities related to that primary entity.
In particular, I have a Supplier class that has one-to-many relation with a Riskset class.
I would like for a user to be able to - on the same page, using the same form - search for a supplier and have the suppliers render using htmx. I would also like for a user to be able to apply filters and have those filters also applied to the same query.
E.g., if a user searches for ‘abc’, suppliers ABC Industries and ABC Inc should appear. This works as expected. The complication is when other filters are included.
I would also like the user to be able to filter by the range of a Supplier’s RiskSet.score and by the Supplier’s RiskSet.threshold. The issue is that whenever a users enters text into any of these fields, the other filters are reset and the queryset object that is returned is only the most recent thing for which the user entered.
Here is the relevant Filter code:
class SupplierFilter(django_filters.FilterSet):
name = django_filters.CharFilter(
lookup_expr='icontains',
label='',
widget=forms.TextInput(attrs={
'hx-get': reverse_lazy('home'),
'hx-target': 'div.table-container',
'hx-swap' : 'outerHTML',
'hx-trigger': 'keyup',
'placeholder': 'Find a supplier...',
'class': 'form-inline form-control mt-3',
})
)
score = django_filters.RangeFilter(
field_name="riskset__score",
label="Supplier Score",
widget=django_filters.widgets.RangeWidget(
attrs={
'hx-get': reverse_lazy('home'),
'hx-target': 'div.table-container',
'hx-swap' : 'outerHTML',
'hx-trigger': 'keyup',
'class': 'form-inline form-control mb-2',
}),
)
turnover = django_filters.RangeFilter(
field_name="riskset__turnover",
label="Turnover",
widget=django_filters.widgets.RangeWidget(attrs={
'hx-get': reverse_lazy('home'),
'hx-target': 'div.table-container',
'hx-swap': 'outerHTML',
'hx-trigger': 'keyup',
'class': "form-inline form-control mb-2",
}),
)
business_type = django_filters.MultipleChoiceFilter(
field_name="business_type",
label="Business Type",
widget=forms.CheckboxSelectMultiple(attrs={
'hx-get': reverse_lazy('home'),
'hx-target': 'div.table-container',
'hx-swap': 'outerHTML',
'hx-trigger': 'keyup',
'class': "form-inline",
'class': 'form-control mt-3', # Make sure to include Bootstrap's form-control class
}),
)
class Meta:
model = Supplier
fields = ['name',]
In action, when a user types a minimum score ‘20’, the query returns results as expected:
After this, if the user then types ‘h’ to search through the suppliers, ‘risk score’ filter is not applied:
Any ideas on how to build and execute this desired functionality using htmx?