Django中如何在商品列表顶部仅显示一次所属分类名称
解决方案
有两种简单的方法可以实现分类名称仅在商品列表顶部显示一次的需求:
方法1:从视图传递分类对象到模板(推荐)
修改你的ProductsListView,重写get_context_data方法,获取当前分类实例并添加到模板上下文:
class ProductsListView(ListView): model = product template_name = 'products/productList.html' context_object_name = 'products' def get_queryset(self, *args, **kwargs): return ( super() .get_queryset(*args, **kwargs) .filter(category_id=self.kwargs['cat_id']) ) # 新增:传递分类对象到模板 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['current_category'] = category.objects.get(id=self.kwargs['cat_id']) return context
然后在模板里直接调用传递过来的分类对象:
{% extends 'products/base.html' %} {% load static %} {% block content %} <h1>Product PAGE!!</h1> <!-- 显示分类名称 --> <h2>{{ current_category.title }}</h2> {% for product in products %} <img src="{{ product.image.url }}" alt="{{ product.name }}" width="10%"> <h2>{{product.name}} </h2> <h2>{{product.cost}} </h2> <h2>{{product.description}} </h2> {% endfor %} {% endblock %}
方法2:从商品列表的第一个元素获取分类(无需修改视图)
如果不想改动视图代码,可以直接从商品查询集的第一个元素提取分类信息,注意先判断列表不为空避免报错:
{% extends 'products/base.html' %} {% load static %} {% block content %} <h1>Product PAGE!!</h1> <!-- 显示分类名称 --> {% if products %} <h2>{{ products.0.category.title }}</h2> {% endif %} {% for product in products %} <img src="{{ product.image.url }}" alt="{{ product.name }}" width="10%"> <h2>{{product.name}} </h2> <h2>{{product.cost}} </h2> <h2>{{product.description}} </h2> {% endfor %} {% endblock %}
为什么products[category]写法无效?
products是Django返回的查询集(QuerySet),属于类列表对象而非字典,无法通过键名(如category)取值,因此该写法会报错。
内容的提问来源于stack exchange,提问作者shubdb
相关产品推荐
相关产品推荐

