Django项目配置求助:Template Does Not Exist错误排查
排查Django模板找不到的问题
1. 核对模板文件路径结构
- 确认应用目录下的模板层级是否正确,必须是:
DrewThe1stBlog/ templates/ DrewThe1stBlog/ post_list.html views.py urls.py - 注意大小写一致性,类Unix系统(Linux、macOS)下文件名/目录名区分大小写,确保
DrewThe1stBlog的拼写和调用模板时完全匹配。
2. 验证settings.py模板配置
- 检查
TEMPLATES配置,确保APP_DIRS设为True,让Django自动扫描已安装应用的templates目录: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', ], }, }, ] - 再次确认
INSTALLED_APPS中确实包含'DrewThe1stBlog',无拼写或引号错误。
3. 检查视图中的模板调用
- 确保视图函数里的模板路径写法正确:
# 正确写法:Django会自动匹配应用templates目录下的对应文件 return render(request, 'DrewThe1stBlog/post_list.html', context) - 避免写错路径,比如直接写
post_list.html(未放在全局模板目录时)或拼写错误的目录名。
4. 清除缓存并重启服务
- 执行命令清除Django缓存:
python manage.py clearcache - 重启开发服务器:
python manage.py runserver
5. 手动排查模板查找路径
- 在视图中添加代码,打印Django的模板查找目录,确认应用的
templates目录是否被包含:from django.template.loader import get_template, TemplateDoesNotExist from django.template.loader import get_app_template_dirs try: template = get_template('DrewThe1stBlog/post_list.html') print("模板路径:", template.origin.name) except TemplateDoesNotExist: print("扫描的应用模板目录:", get_app_template_dirs('templates')) - 启动服务器后查看控制台输出,确认路径是否正确。
内容的提问来源于stack exchange,提问作者drewthe1st
相关产品推荐
相关产品推荐

