如何使用django模板中的嵌套if-else



这里,在这个项目中,我正在构建一个电子商务网站,我正在使用Django。所以,在这里我想表明,如果没有Electric类别的产品,"抱歉,目前没有可用的产品">将显示。其中n是从应用程序视图发送到此模板的产品数量。但我并没有变得"坚强";抱歉,目前没有可用的产品"因为我的数据库中没有Electric类别的产品。如何解决此问题?我哪里做错了?

视图.py

def electric(request):
product = Product.objects.all()
n = len(product)
params = {'product': product, 'range':range(1,n), 'n':n}
return render(request,'electric.html',params)

electrical.html

{% if n is 0 %}
<div class="p-3 mb-1 bg-warning text-white text-center my-0">
<h1><b>Sorry, No Product is Available Right Now !!! </b></h1>
</div>

{% else %}
<div class="album py-2 bg-gradient">
<div class="container">
<div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">

{% for i in product %}
{% if i.category == "Electric" %}
<div class="col">
<div class="card shadow-sm">
<img src="{{i.image}}" />
<div class="card-body">
<h4 class="card-title">{{ i.product_name}}</h4>
<h6 class="card-subtitle mb-2 text-muted">
Category: {{i.category}}
</h6>
<p class="card-text">{{i.description}}</p>
<div class="buy d-flex justify-content-between align-items-center">
<div class="price text-success">
<h5 class="mt-4">Price: {{i.price}} BDT</h5>
</div>
<a href="#" class="btn btn-danger mt-3"><i class="fas fa-shopping-cart"></i> Add to Cart</a>
</div>
</div>
</div>
</div>
{% endif %}      
{% endfor %}

</div>
</div>
</div> 
{% endif %}

views.py

def electric(request):
product = Product.objects.all()
return render(request,'electric.html',{'product': product})

electric.html

{% if  product.count > 0 %}

--  your code  --      
{% else %}
<div class="p-3 mb-1 bg-warning text-white text-center my-0">
<h1><b>Sorry, No Product is Available Right Now !!! </b></h1>
</div>
{% endif %}

如上所述更新您的代码。它会起作用的。

最新更新