Как вывести подкатегории в html Django?
У меня есть подкатегории и я хочу их вывести в шаблон shop.html и вывести их под родителем, Как я могу это сделать?
вот код models.py
from django.db import models
# Create your models here.
class ProductCategory(models.Model):
name = models.CharField(max_length=64, unique=True)
description = models.TextField(blank=True)
parent_category = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)
class Meta:
verbose_name_plural = "Product Categories"
def __str__(self):
if self.parent_category !=None:
return f'{self.name} || {self.parent_category } '
return f'{self.name}'
class Product(models.Model):
name = models.CharField(max_length=256)
image = models.ImageField(upload_to = 'products_images', blank = True)
description = models.TextField(blank=True)
short_description = models.CharField(max_length=64, blank = True)
price = models.DecimalField(max_digits=8, decimal_places=2, default=0)
quantity = models.PositiveIntegerField(default=0)
category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE)
def __str__(self):
return f'{self.name} | {self.category.name}'
Вот Views.py:
from django.shortcuts import render
from products.models import Product, ProductCategory
# Create your views here.
def index(request):
return render(request, 'products/index.html')
def shop(request):
context = {
'categories':ProductCategory.objects.all(),
'products':Product.objects.all()
}
return render(request,'products/shop.html',context )
shop.html:
<div class="container py-5">
<div class="row">
<div class="col-lg-3">
<h1 class="h2 pb-4">Categories</h1>
<ul class="list-unstyled templatemo-accordion">
{% for category in categories %}
<li class="pb-3">
<a class="collapsed d-flex justify-content-between h3 text-decoration-none" href="#">
{{category}}# А тут родительские категории
<i class="fa fa-fw fa-chevron-circle-down mt-1"></i>
</a>
<ul class="collapse show list-unstyled pl-3">
<li><a class="text-decoration-none" href="#">#Вот тут я хочу вывести подкатегории</a></li>
</ul>
</li>
{% endfor %}
</ul>
</div>