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

基于分类展示产品页面:URL传递两个参数的实现问题

修正后的完整实现

1. URL 配置

保持你的URL结构,确保参数顺序匹配(分类slug在前,产品slug在后):

path('category/<str:slug>', views.categoryslug, name="categoryslug"),
path('category/<str:slug>/<str:proslug>', views.catproslug, name="catproslug")

2. 视图函数

分类产品列表视图(categoryslug)

取消return语句的注释,同时用get_object_or_404替代get(),避免分类不存在时抛出服务器错误:

from django.shortcuts import render, get_object_or_404
from .models import Category, Product

def categoryslug(request, slug):
    category = get_object_or_404(Category, slug=slug)
    context = {
        'category': category,
        'products': category.product_set.all(),
    }
    return render(request, 'pages/catpro.html', context)

单个产品详情视图(catproslug)

补充未定义的category变量,同时验证产品是否属于当前分类,防止非法访问:

def catproslug(request, slug, proslug):
    category = get_object_or_404(Category, slug=slug)
    # 额外验证产品归属,确保产品属于当前分类
    product = get_object_or_404(Product, slug=proslug, category=category)
    context = {
        'product': product,
        'category': category
    }
    return render(request, 'pages/catpro.html', context)

注:把原变量名d改成了语义化的product,你也可以保留原命名,但建议用清晰的变量名提升代码可读性。

3. 模板代码

修正{% url %}标签的参数顺序,和URL配置的参数(分类slug、产品slug)对应:

<!-- 在分类产品列表页面中,遍历生成产品链接 -->
{% for product in products %}
    <a href="{% url 'catproslug' category.slug product.slug %}">
        {{ product.name }}
    </a>
{% endfor %}

额外注意事项

  • 确保Product模型中存在关联Category的外键字段
  • 给Category和Product的slug字段添加unique=True约束,避免重复slug导致查询冲突
  • 可以自定义404模板,提升用户访问不存在页面时的体验

内容的提问来源于stack exchange,提问作者dadi game

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:40:49