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

Django渲染home.html输出hello时出现TemplateDoesNotExist错误,附相关代码

Django TemplateDoesNotExist 错误修复方案
  • 修复视图函数参数错误
    views.py 中存在形参名和调用名不匹配的问题,同时多余导入无效模块,修正后代码如下:
from django.shortcuts import render

def home(request):
    return render(request, 'home.html')
  • 确认模板目录结构合规
    你在settings.py中配置了从项目根目录的templates文件夹读取模板,需保证目录结构和以下示例一致:
项目根目录(与manage.py文件同级)
├── 你的应用文件夹
│   ├── views.py
│   ├── urls.py
│   └── 其他应用文件
├── templates
│   └── home.html
└── manage.py

如果你的home.html放在单个应用内部的templates文件夹下,需要先在settings.py的INSTALLED_APPS列表中注册对应应用。

  • 确认模板配置完整
    检查settings.py中TEMPLATES配置块的APP_DIRS参数是否为True,完整配置参考:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(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',
            ],
        },
    },
]
  • 排查文件名大小写问题
    Linux、macOS系统对文件名大小写敏感,需确认模板文件名确实为home.html,无大小写拼写错误。
  • (可选)适配高版本Django路径写法
    如果使用Django3.1及以上版本,框架默认用Path对象定义BASE_DIR,可将DIRS配置修改为以下写法,避免os模块兼容问题:
'DIRS': [BASE_DIR / 'templates'],

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:24:04