How to change the Django admin filter to use a dropdown instead of list?

后端 未结 9 853
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 03:58

If, for a field that you want to filter by, you have more than ~10 values, the filtering sidebar starts to be ugly and harder to use.

I\'m looking for a solution to

相关标签:
9条回答
  • 2020-12-13 04:37

    Use filter.html from feincms

    {% load i18n %}
    <script type="text/javascript">var go_from_select = function(opt) { window.location = window.location.pathname + opt };</script>
    <h3>{{ title }}</h3>
    <ul class="admin-filter-{{ title|cut:' ' }}">
    {% if choices|slice:"4:" %}
        <li>
        <select style="width: 95%;"
            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>
    
    0 讨论(0)
  • 2020-12-13 04:40

    Thanks @beholderrk, @gediminas and @jk-laiho! I packaged this into a reusable app.

    Install:

    pip install django-admin-list-filter-dropdown
    

    Enable in settings.py:

    INSTALLED_APPS = (
        ...
        'django_admin_listfilter_dropdown',
        ...
    )
    

    Use in admin.py:

    from django_admin_listfilter_dropdown.filters import (
        DropdownFilter, ChoiceDropdownFilter, RelatedDropdownFilter
    )
    
    class EntityAdmin(admin.ModelAdmin):
        ...
        list_filter = (
            # for ordinary fields
            ('a_charfield', DropdownFilter),
            # for choice fields
            ('a_choicefield', ChoiceDropdownFilter),
            # for related fields
            ('a_foreignkey_field', RelatedDropdownFilter),
        )
    

    Here's what it looks like:

    Screenshot of dropdown list filter

    0 讨论(0)
  • 2020-12-13 04:40

    The best solution is to create a new template in admin/filter.html and implement the HTML code suggested by @beholderrk. Just implemented it for a client and it works great.

    Problem with DropdownFilter and RelatedDropdownFilter is that it loses the proper display. Instead of the translated strings for Charfield(choices=xxx), it will show True, False and so on.

    0 讨论(0)
提交回复
热议问题