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

部署在Heroku的Django应用出现TemplateDoesNotExist错误求助

排查与解决方案

1. 检查模板文件的Git提交状态

Heroku部署依赖Git仓库内容,若模板文件未被Git追踪提交,服务器上根本不存在该文件:

  • 执行 git status 查看 users/templates/registration/register.html 是否在未追踪列表中
  • 若未追踪,执行 git add users/templates/registration/register.html,提交后重新推送:git commit -m "Add registration template" && git push heroku main

2. 确认Django模板配置正确性

检查settings.py中的模板与应用配置:

# 确保APP_DIRS为True,Django才会自动搜索各app下的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',
            ],
        },
    },
]

# 确认users应用已添加到INSTALLED_APPS
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users',  # 必须存在这一行
    'learning_logs',
]

3. 验证Heroku服务器上的文件结构

通过Heroku CLI登录服务器查看实际文件:

  • 执行 heroku run bash --app your-app-name(替换为你的应用名)
  • 进入目录检查:cd app/users/templates/registration && ls
    • 若看不到register.html,说明文件未上传,回到第一步处理Git提交
    • 若文件存在,继续下一步排查

4. 检查视图中模板的引用路径

视图渲染模板时需使用相对路径,而非绝对路径:

# users/views.py 中的注册视图示例
def register(request):
    # ... 业务逻辑代码
    return render(request, 'registration/register.html', context)

禁止使用/app/users/templates/registration/register.html这类绝对路径,Django会基于配置自动搜索。

5. 清理Heroku构建缓存

缓存可能导致新文件未生效:

  • 执行 heroku repo:purge_cache --app your-app-name
  • 重新推送部署:git push heroku main

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:07:56