У меня есть дерево 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
});