首页 > 解决方案 > django list_filter 不可滚动

问题描述

我有一长串元素(50 个元素),我想将其用作 django 管理面板中的 list_filter 。但是当我使用这个列表时,在过滤器面板出现的最右侧,我只能看到 20 个项目并且它不可滚动,因此其余 30 个被隐藏了。我怎样才能在过滤器部分获得这 30 个项目或如何滚动才能查看所有 50 个项目。

标签: python-3.xdjangodjango-admin-filters

解决方案


您可以为您的字段创建自定义过滤器并使用下拉菜单作为选择器。我强烈建议使用已经提供了几个过滤器的https://github.com/mrts/django-admin-list-filter-dropdown 。

如果您想创建自己的:

管理员.py

from django.contrib.admin.filters import RelatedOnlyFieldListFilter

class RelatedOnlyDropdownFilter(RelatedOnlyFieldListFilter):
    template = 'filters/related_filter.html'

@admin.register(ModelName)
class YourModelAdmin(admin.ModelAdmin):
   
    list_filter = (      
        ('field', RelatedOnlyDropdownFilter),
    )

相关过滤器.html

{% load i18n %}
<script type="text/javascript">var filter_by_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"
        onchange="filter_by_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>

推荐阅读