Reputation: 3
I want to print the subcategory names of each Main Category. The below code is now showing all subcategories for every Main category. How can I do?
index.html
{% for mainCatList in main_cat_list %}
<li class="subMenu"><a>{{ mainCatList.main_category_name }}</a>
<ul>
{% for subCat in cat_list %}
<li><a href="products.html"><i class="icon-chevron-right"></i>{{ subCat.category_name }}</a></li>
{% endfor %}
</ul>
</li>
{% endfor %}
views.html
from django.shortcuts import render
from .models import Product, Category, Main_Category
def homePageView(request):
main_cat_list = Main_Category.objects.all()
cat_list = Category.objects.all()
context = {'main_cat_list': main_cat_list, 'cat_list': cat_list}
return render(request, 'index.html', context)
Upvotes: 0
Views: 63
Reputation: 758
I assume that your Category has foreign key to Main_Catagory. In that case, you can do this
{% for main_cat in main_cat_list %}
<li class="subMenu"><a>{{ main_cat.main_category_name }}</a>
<ul>
{% for sub_cat in main_cat.category_set.all %}
<li><a href="products.html"><i class="icon-chevron-right"></i>{{ sub_cat.category_name }}</a></li>
{% endfor %}
</ul>
</li>
{% endfor %}
Upvotes: 1