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

Django 4.1 Polls教程完成后首页访问出现404错误求助

Django Polls教程后首页404及VSCode导入提示问题解决

已完成Django 4.1 Polls教程,可正常进行问题录入、投票等操作,但从管理页点击“View site”访问localhost:8000时,出现以下404错误:

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

dose/
admin/
The empty path didn’t match any of these.

VSCode中所有导入语句显示“reportMissingModuleSources”错误提示,但除首页外,Python和Django其他功能运行正常。

相关代码

polls/views.py

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils import timezone
from django.views import generic

from .models import Choice, Question


class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """
        Return the last five published questions (not including those set to be
        published in the future).
        """
        return Question.objects.filter(
            pub_date__lte=timezone.now()
        ).order_by('-pub_date')[:5]

mysite/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

from django.urls import path

from . import views


app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

问题解决

1. 首页404问题

当前mysite/urls.py未配置根路径(/)的URL映射,Django找不到匹配路由才返回404,有两种修复方式:

  • 方式一:将Polls首页设为网站根页面
    修改mysite/urls.py,把根路径指向polls的index视图:
from django.contrib import admin
from django.urls import include, path

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

此时访问localhost:8000会直接显示Polls首页。

  • 方式二:保留polls/路径,新增根路径跳转
    如果想保留localhost:8000/polls/访问入口,同时让根路径自动跳转过去,可添加重定向视图:
from django.contrib import admin
from django.urls import include, path
from django.views.generic import RedirectView

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

2. VSCode "reportMissingModuleSources"提示问题

这是VSCode的Python语言服务无法定位Django模块源码路径导致的编辑器提示,不影响实际运行,可通过以下步骤解决:

  • 确认VSCode已选中项目使用的Python虚拟环境:点击左下角状态栏的Python版本,选择对应虚拟环境。
  • 在项目根目录创建.vscode/settings.json文件,添加以下配置(替换为你的虚拟环境路径):
{
    "python.analysis.extraPaths": [
        "./venv/lib/python3.x/site-packages"
    ]
}
  • 重启VSCode,提示即可消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:48:20