Django渲染模板报错:TemplateDoesNotExist问题排查与解决
Django TemplateDoesNotExist 问题解决记录
初始问题
项目文件结构为 Resilience_Radar_R2/Leadership_Questions_App/Leadership_Questions/templates/questions.html,视图函数riskindex尝试渲染questions.html时触发TemplateDoesNotExist: Leadership_Questions/questions.html错误,但index函数可正常返回HttpResponse。尝试调整视图中模板路径、修改路由映射均无效,最终通过重新搭建项目解决问题。
更新记录
将模板路径调整为 Resilience_Radar_R2/Leadership_Questions_App/templates/Leadership_Questions/questions.html 后,访问 http://127.0.0.1:8000/Leadership_Questions_App/riskindex/ 仍报错 TemplateDoesNotExist: /questions.html。
二次更新与经验总结
从头重新搭建项目,复制之前的操作后一切正常。回顾发现,此次未执行以下操作:
- 重命名文件和文件夹修正拼写错误(此前修改后可能遗漏引用或未被系统识别)
- 在Finder中移动文件至指定位置
总结:手动修改文件后若出现异常,有时重新搭建项目反而更高效。
相关代码片段
项目 urls.py
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('Leadership_Questions_App/', include("Leadership_Questions_App.urls")) ]
应用 urls.py
from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("riskindex/", views.riskindex, name="riskindex"), ]
views.py
from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Leadership Questions") def riskindex(request): description = "This is text" return render (request, "Leadership_Questions/questions.html", { "text": description } )
settings.py 模板配置
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ]
模板文件 questions.html
<!DOCTYPE html> <html> <head> <title>Leadership Questions</title> </head> <body> {{ description }} </body> </html>
内容的提问来源于stack exchange,提问作者Jlv
相关产品推荐
相关产品推荐

