[英]Conditional object class template tagging Django
我正在嘗試基於統一模型復制 HTML 卡:
模型.py
class Uniform(models.Model):
category = models.CharField(choices = CATEGORY_CHOICES, max_length=11)
description = models.CharField(max_length = 50)
price = models.FloatField(max_length = 6)
size = models.CharField(choices=CLOTHES_SIZE, max_length=4)
image = models.ImageField(upload_to='uniforms/')
class Meta:
ordering = ['category']
def __str__(self):
return '{}: {} - {} - ${}'.format(self.category, self.description, self.size, self.price)
視圖.py
def item_list(request):
uniform = Uniform.objects.all()
description = Uniform.objects.order_by().values('description').distinct()
category = Uniform.objects.order_by().values('category').distinct()
context = {
'uniform':uniform,
'description': description,
'category': category
}
return render(request, 'apparelapp/item_list.html', context)
html
<div class="row wow fadeIn">
{% for item in description %}
<div class="col-lg-3 col-md-6 mb-4">
<div class="card">
<div class="view overlay">
<img src="" alt="">
<a>
<div class="mask rgba-white-slight"></div>
</a>
</div>
<div class="card-body text-center">
<label>
<h5>{{ item.description }}</h5>
</label>
<h5>
{% if uniform.description %}
<strong>
<label for="">{{ uniform.category }}</label>
</strong>
</h5>
{% endif %}
<!--<h4 class="font-weight-bold blue-text">
<strong>${{item.price}}</strong>
<div class="dropdown">
{% for size in item.size %}
<ul>
{{size}}
</ul>
{% endfor %}
</div>
</h4> -->
</div>
</div>
</div>
{% endfor %}
我得到的是項目描述,而不是項目類別:我想說的是,如果顯示了制服的描述,請顯示制服的類別 - 但它是空白的
我嘗試格式化以僅調用統一類別,但后來我將卡片數量增加了 4 倍(例如:一張用於圍裙小到圍裙超大的卡片)
這是因為您使用錯誤的變量來訪問uniform
的類別。
更容易的是迭代你的Uniform
項目。 您可以將其所有項目傳遞給上下文:
視圖.py
def item_list(request):
uniform = Uniform.objects.all()
context = {'uniform': uniform}
return render(request, 'apparelapp/item_list.html', context)
HTML
<div class="row wow fadeIn">
{% for item in uniform %}
<div class="col-lg-3 col-md-6 mb-4">
<div class="card">
<div class="view overlay">
<img src="" alt="">
<a>
<div class="mask rgba-white-slight"></div>
</a>
</div>
<div class="card-body text-center">
<label>
<h5>{{ item.description }}</h5>
</label>
<h5>
{% if item.description %}
<strong>
<label for="">{{ item.category }}</label>
</strong>
</h5>
{% endif %}
</div>
</div>
</div>
{% endfor %}
</div>
另外,我對您的HTML文件進行了一些格式化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.