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

如何在Django中传递URL中的分类参数至子应用?

解决Django子应用获取主路由分类参数的问题

步骤1:修正主项目的urls.py配置

原配置中的category*/不是Django支持的参数捕获格式,需要改成尖括号定义的参数形式来捕获分类ID:

urlpatterns = [
    # 用<int:category_id>捕获URL中的分类数字ID
    path('category<int:category_id>/', include('student.urls'))
]

步骤2:修改student应用的视图函数

在student/views.py的all视图中添加category_id参数,用该参数过滤对应分类的学生数据:

from django.shortcuts import render
from .models import Student  # 替换为你实际的学生模型

def all(request, category_id):
    # 根据分类ID过滤学生列表(字段名需匹配你的模型结构,比如外键字段是category则用category=category_id)
    students = Student.objects.filter(category_id=category_id)
    return render(request, 'student/all.html', {'students': students})

说明

主路由捕获的category_id会自动传递给子应用student的视图函数,无需修改student/urls.py的配置。访问category1/all/时,category_id会被解析为1,视图就能据此返回对应分类的学生列表。如果你的分类标识是字符串而非数字,可将int替换为str,比如<str:category_slug>。

内容的提问来源于stack exchange,提问作者Rishik Mani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 03:27:20