如何解决Django 4.2运行服务器时的TemplateDoesNotExist错误?
解决Django 4.2中TemplateDoesNotExist(home.html)错误
错误原因分析
从报错信息和项目结构来看,访问根路径/时,geekshows.views.home视图尝试加载home.html模板,但Django在所有预设搜索路径中均未找到该文件:
- 项目根目录的
templates文件夹(F:\Django\geekshows\templates\home.html) - Django内置app的templates目录
course和feesapp的templates目录
你的course app模板采用了app名/模板名的规范结构(如course/course1.html),但根路径视图依赖的home.html并未放置在正确位置。
具体解决方案
方案1:创建项目全局templates文件夹
- 在
F:\Django\geekshows目录下新建templates文件夹。 - 在该文件夹内创建
home.html文件,添加基础内容示例:<!DOCTYPE html> <html> <head> <title>首页</title> </head> <body> <h1>欢迎访问首页</h1> </body> </html> - 确认项目根目录
settings.py中的TEMPLATES配置,确保DIRS项包含根templates路径:from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], # 保证这一行存在且配置正确 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
方案2:将模板放入app的templates目录
如果希望把首页模板归到某个app下(比如course):
- 若直接放在
course的templates根目录:在F:\Django\geekshows\course\templates下创建home.html,视图无需修改路径,保持render(request, 'home.html')即可,Django会自动遍历各app的templates目录查找。 - 若遵循app模板命名空间:将
home.html放在course/templates/course/下,修改geekshows/views.py中的home函数:def home(request): return render(request, 'course/home.html')
额外检查
确认项目根目录urls.py中,根路径/确实指向geekshows.views.home:
from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.home), # 这一行对应根路径的视图 path('admin/', admin.site.urls), path('course/', include('course.urls')), ]
内容的提问来源于stack exchange,提问作者Soumya BTech
相关产品推荐
相关产品推荐

