Django中访问多级课程页面出现404(页面未找到)错误排查
Hey there, let's break down why you're hitting that 404 error when accessing URLs like /courses/1/1/ or /courses/1/2/, and fix it step by step.
问题根源
You're trying to access URLs with two levels of parameters (course ID + step ID), but your current code only has a view (course_detail) that handles a single parameter, plus no matching URL route for the multi-level path. Django can't find a matching view, so it throws the 404.
第一步:新增处理步骤详情的视图
Update your courses/views.py to add a view that handles both course and step IDs. This view will fetch the specific course first, then the matching step under that course:
from django.shortcuts import get_object_or_404, render from .models import Course, Step def course_list(request): courses = Course.objects.all() return render(request, 'courses/course_list.html', {'courses': courses}) def course_detail(request, pk): course = get_object_or_404(Course, pk=pk) return render(request, 'courses/course_detail.html', {'course': course}) # 新增:处理课程下具体步骤的视图 def step_detail(request, course_pk, step_pk): # 先验证课程存在,再验证该课程下的步骤存在 course = get_object_or_404(Course, pk=course_pk) step = get_object_or_404(Step, pk=step_pk, course=course) return render(request, 'courses/step_detail.html', {'course': course, 'step': step})
第二步:配置匹配多级参数的URL路由
Next, add a URL rule that matches the two-level path. If you're using an app-specific urls.py (recommended), modify courses/urls.py like this:
from django.urls import path from . import views urlpatterns = [ path('', views.course_list, name='course_list'), # 注意:更具体的URL要放在更通用的URL前面! path('<int:course_pk>/<int:step_pk>/', views.step_detail, name='step_detail'), path('<int:pk>/', views.course_detail, name='course_detail'), ]
Important: Order matters here. The two-parameter path needs to come before the single-parameter one, otherwise Django will match
/courses/1/1/to thecourse_detailview (using1as the course ID) and ignore the step parameter.
第三步:确认模板文件存在
Make sure you've created a step_detail.html template in courses/templates/courses/ to render the step content. You can populate it with data from the course and step variables passed from the view.
额外检查点
- Verify your
Stepmodel has a foreign key linking toCourse:class Step(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) # Add other fields (like title, content) here - Double-check that you have existing
CourseandStepentries in your database—get_object_or_404will throw a 404 if the requested IDs don't exist.
Once you've made these changes, accessing URLs like http://127.0.0.1:8000/courses/1/1/ should load the correct step detail page without the 404 error.
内容的提问来源于stack exchange,提问作者Ashish Yadav

