Django实现注册登录登出功能遇TemplateDoesNotExist错误求助
模板不存在报错的修复方案
核心问题1:全局模板目录未纳入Django扫描范围
当前settings.py中TEMPLATES配置的DIRS为空列表,默认开启的APP_DIRS=True仅会扫描每个已安装应用内部的templates子目录,完全不会识别你放在项目根目录下的全局templates文件夹。
修复方式:在settings.py中给DIRS配置指向根目录下的templates文件夹的绝对路径,修改后的完整配置如下:
import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 替换原来的空DIRS配置 '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', ], }, }, ]
核心问题2:render方法的模板路径冗余错误
Django加载模板时,会把你传入render的路径,自动拼接到所有已配置的模板根目录(也就是上面设置的全局templates目录、每个应用内的templates目录)后面,传入的路径不需要带templates/前缀。
你当前代码里写的templates/accounts/signup.html,Django实际会查找的路径是:项目根目录/templates/templates/accounts/signup.html,形成了多层嵌套的错误路径,自然找不到文件。
修复方式:把views.py中所有render调用里的模板路径,去掉前面的templates/前缀,示例如下:
# 注册页相关 render 调用修改 # 错误写法:return render(request,'templates/accounts/signup.html', {'error':'Username is already taken!'}) # 正确写法 return render(request, 'accounts/signup.html', {'error':'Username is already taken!'}) # 登录页相关 render 调用修改 # 错误写法:return render(request,'templates/accounts/login.html', {'error':'Username or password is incorrect!'}) # 正确写法 return render(request, 'accounts/login.html', {'error':'Username or password is incorrect!'})
修复后验证步骤
- 保存所有修改的文件,重启Django开发服务器
- 重新访问/accounts/signup/路径,即可正常加载signup.html模板
- 后续如果需要把模板移到accounts应用内部,只要在accounts应用目录下新建
templates/accounts子目录,把对应模板文件移进去即可,不需要额外修改配置,Django会通过APP_DIRS规则自动扫描识别。
内容的提问来源于stack exchange,提问作者user13976637
相关产品推荐
相关产品推荐

