'Customize Django FilterSet: Create custom filter
I have a document table (django-tables2) and a FilterSet (django-filter) to filter it. That works fine in general.
I want to create a custom ModelChoiceFilter (or ChoiceFilter) to display the elements in a two level hierarchy (a tree with parent nodes and one level of children):
+ Category 1
+ Subcategory 1.1
+ Subcategory 1.2
+ Category 2
+ Subcategory 2.1
+ Subcategory 2.2
There is no need to expand and collapse the tree, i just want to show them ordered by category and rendered a little differently if they are first or second level. There are never more than two levels present and each top level component has at least one child.
My current FilterSet looks like this:
class DocumentFilter(FilterSet):
title_name = CharFilter(lookup_expr='icontains')
place_name = CharFilter(lookup_expr='icontains')
source_type = ModelChoiceFilter(queryset=SourceType.objects.all().order_by('type_name'))
doc_start_date = DateFromToRangeFilter()
class Meta:
model = Document
fields = ['title_name', 'source_type', 'place_name', 'doc_start_date']
My model for the SourceType is as follows:
class SourceType(models.Model):
type_name = models.CharField(verbose_name="archivalienart",
max_length=50,)
parent_type = models.ForeignKey('self',
verbose_name="übergeordnete Archivalienart",
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="child_type",)
The filter form template is as follows:
{% load bootstrap4 %}
<form action="{{ request.path }}" method="get" class="form form-inline">
<i class="fas fa-filter"></i>
{% bootstrap_form filter.form layout='inline' form_group_class='my-small-form' %}
{% bootstrap_button '<i class="fas fa-filter"></i>' %}
<a class="btn btn-primary" href='{{ request.path }}'><i class="fas fa-times"></i></a>
</form>
<br/>
I am not sure on how to proceed. As I understand it, what gets rendered are FormFields but I didn't find a way to customize the rendering based on a result list.
So: Where to start? How do I use a custom FormField or a CustomWidget to render <option> tags based on the model object they represent?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

