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

Django教程:访问/polls/<int:question_id>/时出现Page not found错误

问题解决:Django访问polls详情页出现Page not found错误

问题描述

访问地址http://127.0.0.1:8000/polls/1/时收到“Page not found”错误,确认question_id存在(可在shell中查看),且无论输入什么ID都会出现相同问题。

问题代码

views.py

from django.http import HttpResponse, Http404
from django.shortcuts import render, get_object_or_404

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)


def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

polls/urls.py

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('/', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
]

解决方法

问题根源在polls应用的urls.py路径配置:

  • 当前path('/', views.index, name='index')开头带斜杠,而项目根urls.py已通过include('polls.urls')引入polls/前缀,应用内的URL路径无需再以斜杠开头。
  • 这个错误配置会导致Django无法匹配polls/1/这类路径,最终触发404。

修改polls/urls.py的urlpatterns:

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='index'),  # 移除开头的斜杠
    path('<int:question_id>/', views.detail, name='detail'),
]

修改后,访问http://127.0.0.1:8000/polls/1/即可正确匹配detail视图,获取对应Question对象并返回页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 11:35:04