Warm tip: This article is reproduced from stackoverflow.com, please click
django django-models django-templates tree django-forms

How to display a tree in select2?

发布于 2020-03-27 10:20:06

I have a Categories tree (MP_Node). It is necessary to display them in the form of a tree at the 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>

I get select

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

Need to receive

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

js

$('select').select2({
  placeholder: " ",
  minimumResultsForSearch: Infinity
});
Questioner
user11301070
Viewed
98
Christian Žagarskas 2019-07-03 21:57

Was looking for the same thing. Found this: https://github.com/clivezhg/select2-to-tree

Compat: Select2 4+

enter image description here

Also looked at this, but did not use: https://github.com/maliming/select2-treeview