Django 4.1.2出现TemplateDoesNotExist错误,无法渲染模板求助
Django 4.1.2 TemplateDoesNotExist 错误排查与解决
我是Django新手,使用4.1.2版本,创建了名为home的应用,已在主配置文件中配置模板,但仍出现TemplateDoesNotExist错误。
配置代码
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR/'home', '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', ], }, }, ]
视图代码
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return render(request, ' home/welcome.html' , {})
解决方法
- 移除模板路径的多余空格:视图中
' home/welcome.html'开头的空格会导致路径识别错误,改为'home/welcome.html'。 - 规范模板文件结构:确保home应用内的模板目录为
home/templates/home/welcome.html。开启APP_DIRS=True后,Django会自动扫描已注册应用的templates目录,将模板放在与应用同名的子目录下,既符合Django规范,也能避免模板重名冲突。 - 核对路径配置逻辑:如果你的模板直接放在
项目根目录/home/templates下,那视图中应使用'welcome.html'作为路径;但更推荐遵循应用内模板的规范,无需额外配置DIRS即可正常读取模板。
内容的提问来源于stack exchange,提问作者AnonymousScientificUser
相关产品推荐
相关产品推荐

