如何在Django中从分类ListView打开对应分类的品牌ListView
实现分类跳转至对应品牌列表的步骤
1. 给Category模型添加跳转链接方法
在Category模型中新增get_absolute_url方法,自动生成指向该分类品牌列表的URL:
class Category(models.Model): # 原有字段保持不变 def get_absolute_url(self): return reverse('brand_list_by_category', args=[self.pk])
2. 创建品牌列表的ListView
新建一个ListView类,通过URL传递的分类ID过滤出对应品牌:
from django.views.generic import ListView from .models import Brand class BrandByCategoryListView(ListView): model = Brand template_name = 'your_app/brand_list.html' # 替换为你的实际模板路径 context_object_name = 'brands' def get_queryset(self): # 从URL参数中获取分类ID,筛选该分类下的品牌 category_id = self.kwargs.get('category_id') return Brand.objects.filter(category_id=category_id).order_by('brand_name')
3. 配置URL路由
在应用的urls.py中添加路由规则,传递分类ID参数:
from django.urls import path from .views import BrandByCategoryListView, CategoryListView # 导入你已有的分类列表视图 urlpatterns = [ # 原有分类列表路由 path('categories/', CategoryListView.as_view(), name='category_list'), # 新增品牌列表路由,接收category_id参数 path('categories/<int:category_id>/brands/', BrandByCategoryListView.as_view(), name='brand_list_by_category'), ]
4. 修改分类列表模板,添加跳转链接
在分类列表模板(如category_list.html)中,给每个分类名称添加跳转链接:
{% for category in category_list %} <div class="category-item"> <a href="{{ category.get_absolute_url }}">{{ category }}</a> {% if category.category_picture %} <img src="{{ category.category_picture.url }}" alt="{{ category }}"> {% endif %} </div> {% endfor %}
5. 编写品牌列表展示模板
创建brand_list.html模板,展示过滤后的品牌信息:
<h2>当前分类:{% if brands %}{{ brands.first.category }}{% else %}无{% endif %}</h2> <div class="brand-list"> {% for brand in brands %} <div class="brand-item"> <h3>{{ brand.brand_name }}</h3> <p>所属国家:{{ brand.brand_country }}</p> <p>品牌简介:{{ brand.brand_story|truncatewords:20 }}</p> </div> {% empty %} <p>该分类下暂无品牌</p> {% endfor %} </div>
内容的提问来源于stack exchange,提问作者Thomas Doll-Datema
相关产品推荐
相关产品推荐

