温馨提示:本文翻译自stackoverflow.com,查看原文请点击:django - How to display a tree in select2?

django - 如何在select2中显示树?

发布于 2020-03-27 10:48:05

我有一Categories棵树(MP_Node)。有必要在树上以树的形式显示它们select2

models.py

class Category(MP_Node):
    ....

表格

class ProductCreateForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = (
            ...., 'category', ....
        )

    def __init__(self, *args, **kwargs):
        super(ProductCreateForm, self).__init__(*args, **kwargs)
        self.fields['category'].empty_label = None
        self.fields['category'] = ModelChoiceField(queryset=Category.objects.all(), widget=forms.Select(
            attrs={'class': 'select2', 'style': 'width: 165px'}))

html

<div class="field inline select">
      <label for="id_category" class="subhead">Категория:</label>
      <select name="category" style="width: 165px" required="" class="select2 select2-hidden-accessible" id="id_category" tabindex="-1" aria-hidden="true">
        <option value="" selected="">---------</option>
        <option value="1">Food</option>
        <option value="4">Meal</option>
        <option value="2">Sweet</option>
        <option value="3">Milk</option>
        <option value="9">Sport</option>
        <option value="6">Football</option>
        <option value="7">Ball</option>
        <option value="5">Form</option>
        <option value="8">Shirt</option>
        <option value="10">T-Shirt</option>
        <option value="11">Attribute</option>
      </select>
      <span class="select2 select2-container select2-container--default select2-container--focus" dir="ltr" style="width: 165px;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-id_category-container"><span class="select2-selection__rendered" id="select2-id_category-container"><span class="select2-selection__placeholder"> </span></span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>
    </div>

我选择

Food
Meal
Sweet
Milk
Sport
Football
Ball
Form
Shirt
T-Shirt
Attribute

需要接收

Food
  Meal
  Sweet
  Milk
Sport
  Football
    Ball
    Form
      Shirt
      T-Shirt
    Attribute

js

$('select').select2({
  placeholder: " ",
  minimumResultsForSearch: Infinity
});

查看更多

查看更多

提问者
user11301070
被浏览
41
Christian Žagarskas 2019-07-03 21:57

在寻找相同的东西。找到了这个:https : //github.com/clivezhg/select2-to-tree

兼容:Select2 4+

在此处输入图片说明

还看着这个,但没有使用:https : //github.com/maliming/select2-treeview

发布
问题

分享
好友

手机
浏览

扫码手机浏览