Django报错:Template does not exist及Page Not Found问题排查求助
Django 新手求助:「Template does not exist」和「Page Not Found」错误
我是Django新手,使用最新版本时遇到「Template does not exist」和「Page Not Found」错误。已按自身认知配置路由与视图,附上相关代码及目录结构,恳请帮忙定位问题。
相关代码
应用 urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ]
视图代码
from django.shortcuts import render from requests import request # Create your views here. def index(request): return render(request, 'landing_page/index.html')
项目 urls.py
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('/', include('comp.urls')), path('admin/', admin.site.urls), ]
目录结构

问题定位与修复方案
1. 路由配置错误(引发「Page Not Found」)
项目根urls.py中path('/', include('comp.urls'))写法错误:Django路径匹配会忽略开头的斜杠,且根路径需用空字符串''配置,否则无法正确匹配访问请求。修正后代码:
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('comp.urls')), # 移除开头斜杠 path('admin/', admin.site.urls), ]
2. 模板路径与导入错误(引发「Template does not exist」)
- 视图中错误导入
from requests import request,会覆盖Django原生的request对象,必须删除该行。 - 从目录结构看,模板文件实际位于
comp/templates/comp/index.html,但视图中写的是landing_page/index.html,路径不匹配。修正后视图代码:
from django.shortcuts import render # Create your views here. def index(request): return render(request, 'comp/index.html') # 改为对应应用下的模板路径
3. 验证模板目录规范
确保模板目录遵循Django约定结构,避免命名冲突:
comp/ ├── templates/ │ └── comp/ │ └── index.html ├── urls.py ├── views.py
同时确认项目settings.py中APP_DIRS = True(默认开启),Django会自动搜索各应用下的templates目录。
内容的提问来源于stack exchange,提问作者TrevTheDev
相关产品推荐
相关产品推荐

