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

Django教程任务3配置完成后运行服务无法访问polls路径

问题根源

你把项目级路由和polls应用级路由的配置写在了同一个文件里,路由规则冲突+应用路由文件缺失,是导致访问polls路径404的核心原因。

  • 你贴出的urls.py同时混杂了仅能写在项目根urls.py的include('polls.urls')、admin路由规则,和仅能写在polls应用自身urls.py的index、detail等子路由规则,Django解析路由时无法正确匹配路径。
  • 你当前的index视图直接返回拼接的字符串,没有调用你写的index.html模板,就算路由修复完成,也不会渲染模板内容。
修复步骤

1. 拆分两类路由配置

找到和settings.py同层级的项目根目录下的urls.py,删除多余内容,仅保留根路由规则:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

进入polls应用文件夹,新建urls.py文件(如果已存在就清空原有错误内容),写入polls的子路由规则:

from django.urls import path
from . import views

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

2. (按需修改)配置模板渲染

如果需要加载你写的index.html模板,先在polls目录下新建层级结构templates/polls/,把index.html放到这个目录里,再修改views.py的index视图:

from django.http import HttpResponse
from django.shortcuts import render
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):
    return HttpResponse("You're looking at question %s." % question_id)

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

如果暂时不需要用模板,保持你原来的index视图返回字符串的写法也可以,不影响路由正常访问。

3. 执行数据库迁移

如果还没执行过模型迁移,查询Question表会报错,在项目根目录执行两条命令:

python manage.py makemigrations
python manage.py migrate

4. 重启服务验证

停掉当前运行的开发服务器,重新执行python manage.py runserver启动,访问http://127.0.0.1:8000/polls/即可正常访问。

注意:如果页面显示No polls are available.,说明数据库里还没有Question测试数据,可以先访问admin后台添加数据后再查看效果。

内容的提问来源于stack exchange,提问作者Dollar Tune-bill

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 05:55:16