【发布时间】:2017-03-07 23:47:24
【问题描述】:
我已经尝试做这个嵌套循环几个小时了,但到目前为止我的结果都没有奏效。这是我目前所拥有的:
index.html
{% for category in categories %}
<div class="col-md-12 column category list-group">
<p><b>{{ category.name }}</b></p>
{% for subcategory in subcategories %}
<div class="list-group-item">
<h5 class="mb-1"><a href="{% url 'subcategory_threads' subcategory.id %}">{{ subcategory.name }}</a></h5>
<small>{{ subcategory.description }}</small>
<small>{{ subcategory.count_threads }}</small>
</div>
{% endfor %}
</div>
{% endfor %}
views.py
class IndexView(ListView):
template_name = 'myForum/index.html'
context_object_name = 'SubCategory_list'
queryset = SubCategory.objects.all()
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['categories'] = Category.objects.all()
context['subcategories'] = SubCategory.objects.all()
return context
models.py
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class SubCategory(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=255)
category = models.ForeignKey('Category', default=0)
def __str__(self):
return self.name
输出 Output
我的问题是 SubCategory - News,属于 Infromation,类别 Off-Topic 属于 General。由于某种原因,循环显示所有子类别,我不知道如何将其缩小到当前类别。
【问题讨论】:
标签: python django loops templates for-loop