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>
问题排查与修复
- 模板标签语法错误
HTML模板里的链接生成标签缺少百分号,正确写法应为{% url 'collectionsview' item.slug %},修正后:
<a href="{% url 'collectionsview' item.slug %}">
- URL路由与跳转匹配问题
- 路由
path('collaction', views.collactions, name="collactions"),末尾缺少斜杠,会导致路由匹配异常,改为path('collaction/', views.collactions, name="collactions"),。 - 视图中
redirect('collections')的名称与URL配置里的name="collactions"不匹配,改为redirect('collactions')。
- 模型类名规范问题
Django模型类通常采用大驼峰命名(如Product),代码中product.objects.filter如果模型实际类名为Product,会引发报错,修正为:
products = Product.objects.filter(category__slug=slug)
- 变量命名优化(可选)
Categorys建议改为categories,符合Python小写开头的命名规范,不影响功能但提升代码可读性。
按上述修正后,按类别展示商品的功能即可正常运行。
内容的提问来源于stack exchange,提问作者mahmoud abdel hadi charef
相关产品推荐
相关产品推荐

