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

Django开发遇TemplateDoesNotExist错误:基础表单实现问题求助

Django TemplateDoesNotExist 错误解决:找不到 basicapp/index.html

错误详情

TemplateDoesNotExist at /
basicapp/index.html
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 4.1.3
Exception Type: TemplateDoesNotExist
Exception Value:    
basicapp/index.html
Exception Location: C:\Users\ADMIN\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template\loader.py, line 19, in get_template
Raised during:  basicapp.views.index
Python Executable:  C:\Users\ADMIN\AppData\Local\Programs\Python\Python311\python.exe

Python Version: 3.11.0

Template-loader postmortem
Django tried loading these templates, in this order:

Using engine django:

django.template.loaders.filesystem.Loader: C:\Users\ADMIN\Desktop\Django\Django_forms\basic_forms\templates,\basicapp\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\ADMIN\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\admin\templates\basicapp\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\ADMIN\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\templates\basicapp\index.html (Source does not exist)

问题根源

从模板加载路径可见,filesystem.Loader尝试访问的路径包含templates,(多了一个逗号),这是settings.py中模板目录路径配置错误导致的。同时需要确认模板文件的存放结构是否符合Django的查找规则。

修复步骤

1. 修正模板目录路径配置

打开settings.py,找到TEMPLATE_DIR的定义,删除字符串中的多余逗号:

# 原错误代码
TEMPLATE_DIR = os.path.join(BASE_DIR,"templates,")

# 修改后正确代码
TEMPLATE_DIR = os.path.join(BASE_DIR,"templates")

2. 确认模板文件结构

确保模板文件的存放路径符合以下两种结构之一:

  • 项目级模板目录(对应DIRS配置):
    basic_forms/  # 项目根目录
    ├── templates/
    │   └── basicapp/
    │       ├── index.html
    │       └── form_page.html
    ├── basicapp/
    └── ...
    
  • App级模板目录(对应APP_DIRS=True配置):
    basicapp/
    ├── templates/
    │   └── basicapp/
    │       ├── index.html
    │       └── form_page.html
    ├── views.py
    ├── forms.py
    └── ...
    

3. 验证模板加载配置

确保settings.py中的TEMPLATES配置正确,APP_DIRS设为True以启用app内模板查找:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        'APP_DIRS': True
    }
]

验证

修改完成后,重启Django开发服务器,访问http://127.0.0.1:8000/,若路径配置和文件结构正确,页面将正常加载。

内容的提问来源于stack exchange,提问作者Jay Wandery

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:05:16