The goal of my fork was to create an easy way to add filters in ModelAdmin, simply setting an attribute that I named ‘advanced_search_fields’. In the following, ‘advanced_search_fields’ refers to a filter that allows to filter the fields independently and is clearly implemented with a FilterSet form.
In my current implementation, the presence of attribute advanced_search_fields on ModelAdmin generates a button that will display the form filter when clicked. As in most other django ModelAdmin attributes there’s also a function named get_advanced_search_fields (same signature as get_search_fields) that you can use to customize the advanced_search field at runtime. This method takes precedence over the attribute.
Below you can find the features I added to django-filters:
I realized that in many circumstancies I needed to create a FilterSet class just to set the lookup_type for each field, so I modified it in a way that accept the lookup_type to be added to the field_name:
class CertificateAdmin(DjangoFiltersModelAdmin):
model = Certificates
advanced_search_fields = (
('start_date__gte', 'start_date__range', 'user'),
('status__in', 'description__icontains',),
)
in case the field has choices, I fill the widget with them. In case the lookup_type is ‘in’ I set a MultipleChoices
Boolean fields has a default that is ‘——’
When the lookp type is ‘range’ I use the DateRangeFilter. This definetely reflects a personal choice.
My working implementation to get advance_search in admin pages is split in different places:
change_list.html: | |
---|---|
added 2 templatetags:
|
|
ModelAdmin: | added/customized several methods:
|
ChangeList: | currently I customized the ‘get_filters’ method, to clean self.params from filters already used. |
templatetags: |
|
advanced_search.js: | |
|
Integrating this into the admin is quite simple. You just need to:
declare django-filter early in INSTALLED_APPS. So doing change_list.html will be used instead of django.contrib.auth’s one
declare in TEMPLATE_LOADER ‘django_filters.admin.Loader’ that implements the template syntax:
admin:admin/change_list.html
so that we don’t need to overwrite the whole template
derive your ModelAdmin class from django_filters.admin.AdvancedSearchModelAdmin
make your change_list extend django_filters:admin/change_list.html
declare one of:
What I described aove is a working setup that I already have in production, but I’m sure it would need some ironing before considering it for django-filters integration. As you can see it touches several different parts but if django-filters should integrate templates/ModelAdmin could be as easy as declaring your ModelAdmin as descendent of django-filter’s ModelAdmin and placing django_filter early enought in INSTALLED_APPS to thatit’s change_list.html is found before django’s one.