You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何搭建Django主分类页面?层级分类路由视图问题求助

解决主分类页面无法访问的问题

1. 修改URL配置

现有路由仅匹配category/后带层级内容的路径,无法匹配空路径的主分类页。需要添加一条匹配空路径的路由:

# urls.py
from django.urls import path, re_path

# 主分类页路由
path('category/', show_category, name='category_root'),
# 保留原有的层级分类路由
re_path(r'^category/(?P<hierarchy>.+)/$', show_category, name='category'),

2. 调整视图函数

在视图中增加对hierarchy为None的判断,处理主分类页逻辑——返回所有根分类(parent为None的分类):

# views.py
def show_category(request, hierarchy=None):
    if not hierarchy:
        # 主分类页面:获取所有无父级的根分类
        root_categories = Categories.objects.filter(parent=None)
        return render(request, 'shop/categories.html', {'categories': root_categories})
    
    category_slug = hierarchy.split('/')
    parent = None
    root = Categories.objects.all()

    for slug in category_slug[:-1]:
        parent = root.get(parent=parent, slug=slug)

    try:
        instance = Categories.objects.get(parent=parent, slug=category_slug[-1])
    except Categories.DoesNotExist:  # 避免裸except,指定捕获分类不存在的异常
        instance = get_object_or_404(Goods, slug=category_slug[-1])
        return render(request, "shop/product.html", {'instance': instance})
    else:
        return render(request, 'shop/categories.html', {'instance': instance})

3. 模板适配(可选)

如果原有categories.html仅处理单个分类实例,需调整模板逻辑以支持根分类列表:

<!-- shop/categories.html -->
{% if categories %}
    <!-- 主分类页:遍历所有根分类 -->
    {% for category in categories %}
        <a href="{% url 'category' category.slug %}">{{ category.name }}</a>
    {% endfor %}
{% else %}
    <!-- 子分类页:显示单个分类内容 -->
    <h1>{{ instance.name }}</h1>
    <!-- 其他子分类相关内容 -->
{% endif %}

内容的提问来源于stack exchange,提问作者Nikita Mikheev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 09:39:26