【问题标题】:How to use Select2 in Django custom SimpleListFilter如何在 Django 自定义 SimpleListFilter 中使用 Select2
【发布时间】:2020-04-08 08:42:21
【问题描述】:

我创建了一个自定义 SimpleListFilter 类(代码如下)并设法将选项显示为选择输入。我想补充的是 Select2 提供的功能,即能够在选择输入中搜索选项。

谁能告诉我如何做到这一点?

自定义 SimpleListFilter 类:

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:(从我忘记的源代码复制,所以我不相信这段代码)

{% 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>

【问题讨论】:

    标签: django django-admin jquery-select2 django-autocomplete-light django-select2


    【解决方案1】:

    如果您使用的是 Django 2 或更新版本,那么 Django Admin Autocomplete Filter 似乎就是您正在寻找的东西。我没用过,但如果你还没有找到解决方案,这可能值得一试。

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

    【讨论】:

      猜你喜欢
      • 2020-12-15
      • 2022-07-12
      • 1970-01-01
      • 2014-09-21
      • 2012-03-31
      • 2011-04-16
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多