如何在select2中显示树?

时间:2019-05-14 10:30:01

标签: django django-models tree django-forms django-templates

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

models.py

class Category(MP_Node):
    ....

forms.py

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
});

2 个答案:

答案 0 :(得分:1)

正在寻找同一件事。 找到了这个:https://github.com/clivezhg/select2-to-tree

兼容:Select2 4 +

enter image description here

也查看了此内容,但未使用:  https://github.com/maliming/select2-treeview

答案 1 :(得分:0)

使用django-select2有效显示树结构