django - 如何在select2中显示一棵树?
问题描述
我有一Categories
棵树(MP_Node
)。有必要将它们以树的形式显示在select2
.
模型.py
class Category(MP_Node):
....
表格.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
});
解决方案
使用django-select2有效展示树形结构
推荐阅读
- python - 在 pandas 中进行几乎不完整的数据透视表操作
- c++ - 从加密字符串程序获取输出时出现逻辑错误。
- python - mlxtend 中 StackingClassifier 函数中的元分类器是什么?
- mysql - 在 mysql 中使用 group_concate 按类别分隔显示调查结果
- python - 缩放数据的正确方法
- php - array_push 中的回显值
- python - 如何遍历列表列表
- css - 如何将 css-loader 从 v0.28 升级到 v1.0.0?
- html - 使用 CSS 垂直向下或向上定位 Div
- flutter - 使用新的 Flutter 项目进行 Travis-CI 构建的问题