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

Django DEBUG设为False时Heroku返回500错误的排查求助

问题:Heroku部署Django后DEBUG=False时前端模板返回500错误,/admin后台正常访问

本地环境可正常访问mysite.com,部署到Heroku后,仅当配置变量DJANGO_DEBUG设为True时网站可访问。DEBUG=False时,前端模板页面返回500服务器错误,但/admin后台能正常访问,初步推测是模板或文件路径问题。

项目结构:根目录包含myprojectwebsite子目录和全局模板目录templates,本地或DEBUG=True时模板加载正常,生产环境(DEBUG=False)下无法加载。


相关配置与代码

settings.py

from pathlib import Path
import os
from dotenv import load_dotenv
import dj_database_url
import django_heroku

load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False'


ALLOWED_HOSTS = ['myprojectwebsite.herokuapp.com', 'www.mysite.com', 'mysite.com', 'localhost', '127.0.0.1']


INSTALLED_APPS = [
    'myprojectwebsite',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_google_fonts',
    'django.contrib.sitemaps',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'myproject.urls'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'detailed': {
            'format': '{levelname} {asctime} {module} {message} {pathname}:{lineno}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'detailed',
        },
    },
    'loggers': {
        'script_logger': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
    },
}

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],  # Global templates folder
        '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',
                'django.template.context_processors.media',
                'myprojectwebsite.context_processors.resorts_by_location',
            ],
        },
    },
]

WSGI_APPLICATION = 'myproject.wsgi.application'


if DEBUG:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': os.environ.get('DB_NAME', 'myprojectdb'),
            'USER': os.environ.get('DB_USER', 'user'),
            'PASSWORD': os.environ.get('DB_PASSWORD', 'pass'),
            'HOST': os.environ.get('DB_HOST', 'localhost'),
            'PORT': os.environ.get('DB_PORT', ''),
        }
    }
else:
    DATABASES = {
        'default': dj_database_url.config(default=os.environ.get('DATABASE_URL'))
    }


LOGIN_REDIRECT_URL = '/'

LOGOUT_REDIRECT_URL = '/'

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.mailgun.org'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.getenv('MAILGUN_DOMAIN')
EMAIL_HOST_PASSWORD = os.getenv('MAILGUN_API_KEY')


AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
STATIC_URL = '/static/'
GOOGLE_FONTS = ["Roboto"]
# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

SECURE_HSTS_SECONDS = 31536000  # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

django_heroku.settings(locals())

示例模板faq.html

{% extends 'base.html' %}
{% block title %}FAQs{% endblock %}
{% block description %}Example.{% endblock %}
{% block content %}
<div class="container mt-4">
    <h1>Frequently Asked Questions</h1>

    {% for faq in faqs %}
    <div class="faq-item">
        <p><strong>{{ faq.question }}</strong></p>
        <p>{{ faq.answer|safe }}</p>
    </div>
    {% endfor %}
</div>
{% endblock %}

views.py对应视图函数

def faq_view(request):
    faqs = [
        {"question": "Question", "answer": "Answer"},
    ]
    return render(request, 'faq.html', {'faqs': faqs})

urls.py对应路由

path('frequently-asked-questions/', faq_view, name='faq'),

已尝试操作:修改Heroku配置变量、调整settings.py、执行collectstatic和migrate命令,排除数据库问题(/admin正常访问)。


排查方向

  • 查看生产环境详细错误日志:在本地终端执行heroku logs --tail,获取DEBUG=False时500错误的具体堆栈信息,这是定位问题最直接的方式,能明确是模板加载失败、上下文处理器错误还是静态资源问题。
  • 检查全局模板目录的Git提交状态:确认templates目录未被.gitignore规则忽略,Heroku仅同步Git仓库中的文件,若目录未提交会导致生产环境缺失模板。
  • 验证模板路径配置:在settings.py中添加日志输出,打印os.path.join(BASE_DIR, 'templates')的实际路径,确认生产环境下该路径存在且包含所需模板文件。
  • 排查自定义上下文处理器:自定义上下文处理器myprojectwebsite.context_processors.resorts_by_location可能在DEBUG=False时抛出异常(比如依赖DEBUG环境变量、数据库查询失败),可临时注释该处理器并重新部署测试,若问题解决则针对性修复该处理器。
  • 检查静态资源引用:前端模板中若直接使用硬编码路径引用静态资源,DEBUG=False时会因静态资源已被收集到staticfiles目录而无法访问,需确保所有静态资源引用使用{% static %}模板标签。
  • 验证django_heroku配置影响:django_heroku.settings(locals())可能覆盖了模板或静态文件的默认配置,尝试注释该代码并重新部署,若问题解决则逐步排查该函数修改的具体配置项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 07:54:56