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

Django按类别展示商品功能异常排查求助

输入图片描述

我想要实现按类别展示商品的功能,但遇到了一个无法解决的问题,尽管尝试排查却始终找不到问题所在。


URL配置

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', views.home, name="home"),
    path('collaction', views.collactions, name="collactions"),
    path('collaction/<str:slug>/', views.collectionsview, name="collectionsview"),
]

视图代码

from django.shortcuts import render
from .models import *

# Create your views here.
def home(request):
    return render(request, 'store/index.html')

def collactions(request):
    Categorys = Category.objects.filter(status=0)
    context = { 'Categorys':Categorys}
    return render(request, 'store/layout/collaction.html', context)

def collectionsview(request, slug):
    if(Category.objects.filter(slug=slug, status=0)):
        products = product.objects.filter(category__slug=slug)
        category_name = Category.objects.filter(slug=slug).first()
        context = {'products':products, 'category_name':category_name}
        return render(request, "store/products/index.html", context)
    else:
        return redirect('collections')

分类页面HTML模板

{% extends 'store/layout/main.html' %}

{% block content %}
    
    <h1>collaction</h1>
    <div class="row">
        {% for item in Categorys %}
            <div class="col-md-4">
                <div class="card">
                    <a href="{url 'collectionsview' item.slug}">
                        <div class="card-body">
                            <div class="category-image">
                                <img src="{{item.image.url}}"/>
                            </div>
                            <h4>{{ item.name }}</h4>
                        </div>
                    </a>
                </div>
            </div>  
        {% endfor %}
    </div>

问题排查与修复

  1. 模板标签语法错误
    HTML模板里的链接生成标签缺少百分号,正确写法应为{% url 'collectionsview' item.slug %},修正后:
<a href="{% url 'collectionsview' item.slug %}">
  1. URL路由与跳转匹配问题
  • 路由path('collaction', views.collactions, name="collactions"),末尾缺少斜杠,会导致路由匹配异常,改为path('collaction/', views.collactions, name="collactions"),。
  • 视图中redirect('collections')的名称与URL配置里的name="collactions"不匹配,改为redirect('collactions')。
  1. 模型类名规范问题
    Django模型类通常采用大驼峰命名(如Product),代码中product.objects.filter如果模型实际类名为Product,会引发报错,修正为:
products = Product.objects.filter(category__slug=slug)
  1. 变量命名优化(可选)
    Categorys建议改为categories,符合Python小写开头的命名规范,不影响功能但提升代码可读性。

按上述修正后,按类别展示商品的功能即可正常运行。

内容的提问来源于stack exchange,提问作者mahmoud abdel hadi charef

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 23:02:42