如何在django中生成多级列表?我正在尝试编写一个简单的代码,用于显示带子类别的类别,以及用于子论坛的论坛。
它应该是这样的:
Category-1
- Subcategory-1
- Subcategory-2
- Subcategory-3
这是我的代码:
CATEGORY_CHOICES = (
('hw', "Hardware"),
('soft', "Software"),
('snd', 'Audio'),
)
category = models.CharField(max_length=32, choices=CATEGORY_CHOICES)
subcategory = models.CharField(unique=True, max_length=32, blank=True)
{%for c in category %}
{{ c.get_category_display|title }}
{{ c.subcategory }}
<br>
{%endfor%}
答案 0 :(得分:0)
您可以使用optgroups
在您的django表单中,您可以这样设置它们。
def categories_as_optgroups(categories, subcategories):
"""
Create optgroups for sorting activities into programs
"""
subcategory = []
for category in categories:
subcategories_list = []
for subcategory in subcategories.objects.filter(category_fk=category).order_by('name'):
subcategories_list.append([subcategory.id, subcategory.name])
categories_list = [category.name, subcategories_list]
subcategory.append(categories_list)
return activities
class ActivityForm(ModelForm):
program = forms.ModelChoiceField(queryset=Program.objects.all().order_by('name'))
class Meta:
model = BookingActivity
def __init__(self, *args, **kwargs):
super(ActivityForm, self).__init__(*args, **kwargs)
self.fields['activity'].choices = categories_as_optgroups(Programs, Activities)
我用它将activities
分类为programs
作为子组。效果很好。