How to use Select2 in Django custom SimpleListFilter

459 Views Asked by At

I've created a custom SimpleListFilter class (code below) and managed to have the options be displayed as a select input. What I'd like to add is the functionality that Select2 offers, namely being able to search for options within the select input.

Can anyone tell me how to achieve this?

Custom SimpleListFilter class:

class AnswerTreeKnowledgeCodeListFilter(admin.SimpleListFilter):
    template = 'admin/dropdown_filter.html'
    title = _('Kenniscode')

    parameter_name = "knowledge_code"

    def lookups(self, request, model_admin):
        return [(instance.pk, str(instance)) for instance in AnswerTreeRepository.filter_by_level(0)]

    def queryset(self, request, queryset):
        # Custom queryset filtering here

dropdown_filter.html: (copied from source that I forgot, so I take no credit for this code)

{% load i18n %}
<script type="text/javascript">var go_from_select = function(opt) { window.location = window.location.pathname + opt };</script>
<h3>{% blocktrans with title as filter_title %} By {{ filter_title }} {% endblocktrans %}</h3>
<ul class="admin-filter-{{ title|cut:' ' }}">
{% if choices|slice:"4:" %}
    <li>
    <select class="form-control" style="width: 95%;margin-left: 2%;"
        onchange="go_from_select(this.options[this.selectedIndex].value)">
    {% for choice in choices %}
        <option{% if choice.selected %} selected="selected"{% endif %}
         value="{{ choice.query_string|iriencode }}">{{ choice.display }}</option>
    {% endfor %}
    </select>
    </li>
{% else %}

    {% for choice in choices %}
            <li{% if choice.selected %} class="selected"{% endif %}>
            <a href="{{ choice.query_string|iriencode }}">{{ choice.display }}</a></li>
    {% endfor %}

{% endif %}
</ul>
1

There are 1 best solutions below

0
On

Django Admin Autocomplete Filter seems to be what you're looking for, if you're on Django 2 or newer. I haven't used it, but if you haven't found a solution yet, this might be worth trying.

https://github.com/farhan0581/django-admin-autocomplete-filter