将DEBUG设置为False会导致500错误。

327
一旦我更改了DEBUG = False,我的网站会生成500错误(使用wsgi和manage.py runserver),而且在Apache错误日志中没有错误信息。当我将debug更改为True时,它会正常运行。
我正在使用Django 1.5和Python 2.7.3这里是Apache访问日志,并且在Apache错误日志中没有任何日志。
www.beta800.net:80 222.247.56.11 - - [28/Feb/2013:13:42:28 +0800] "GET / HTTP/1.1" 500 257 "-" "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22"
www.beta800.net:80 222.247.56.11 - - [28/Feb/2013:13:42:28 +0800] "GET /favicon.ico HTTP/1.1" 500 257 "-" "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22"
www.beta800.net:80 222.247.56.11 - - [28/Feb/2013:13:42:28 +0800] "GET /favicon.ico HTTP/1.1" 500 257 "-" "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22"

这是我的设置文件:

import os.path    
DEBUG = False 
#TEMPLATE_DEBUG = DEBUG

HERE = os.path.dirname(__file__)
ADMINS = (
    ('admin', 'xyzadmin@qq.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'zdm',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': 'passwd',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
#STATIC_ROOT = os.path.join(HERE, 'static').replace('\\','/')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
#STATIC_ROOT = os.path.join(HERE, 'static').replace('\\','/')
S= os.path.join(HERE, 'static').replace('\\','/')

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    '/home/zdm/static',
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '9a7!^gp8ojyk-^^d@*whuw!0rml+r+uaie4ur$(do9zz_6!hy0'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'zdm.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'zdm.wsgi.application'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    '/home/zdm/templates',
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'zdm',
    'portal',
    'admin',
    'tagging',
)

是的,我已经在我的模板目录中添加了403和404 500 HTML文件。 - zhiguo.wang
1
你的项目中是否已经放置了500.html、404.html和403.html文件?我记得曾经在一个部署的项目中遇到过这样的问题,那个项目的根目录下没有这些文件。 - esse
在我的问题中添加一些访问日志。谢谢。 - zhiguo.wang
102
既然你的SECRET_KEY已经公开,你可能想要更改它了... - ashastral
1
这并不适用于所有人。如在https://dev59.com/PWUp5IYBdhLWcg3wrI7T#37218484中所示,可能会有许多原因导致此问题发生。通过一些简单的记录,您可以在没有猜测的情况下找出原因。 - Rob
显示剩余2条评论
33个回答

7

ALLOWED_HOSTS不是唯一的问题,对我来说,我必须创建一个404.html并将其放在我的模板的基础级别(而不是应用级别) - 另外,您可以创建一个404视图并添加一个404处理程序URL,但我认为这是可选的。 404.html解决了它。

在mainproject.urls中

handler404 = 'app.views.custom_404'

在 app.views 中

def custom_404(request):
    return render(request, '404.html', {}, status=404)

然后制作一个 templates/404.html 模板。

我是从另一个 S/O 帖子上得到这个信息的,但现在找不到了。

编辑

此外,当我使用 whitenoise 服务静态资源时,会出现500错误。我无论如何都无法解决这个问题,错误来自于 whitenoise 找不到一些资源,这些资源我也找不到,只能暂时使用默认的 Django 服务。


11
我跟白噪声有同样的问题。运行命令 python manage.py collectstatic 解决了它。 - Eugene Pakhomov
1
@amchungh89,你真是救星!感谢你指出了那个问题。 - Deepak Sharma
handler404 也解决了我的问题。 - washiur17

7
我有一个非常有趣的故事。在打开这个页面后,我说:“哎呀!太好了,我的问题解决了。”于是我在setting.py中插入了所需的ALLOWED_HOSTS列表,但是出现了相同的500错误。不要误会,这并不是因为缺少404.html文件之类的原因。接下来的两天里,我忙于猜测一些奇怪的理论,比如与静态文件服务有关(请理解我是新手,新手们不知道自己在做什么)。
那么,问题到底出在哪里呢?现在我来告诉大家一个有用的技巧。我的开发Django版本是1.5.x,而生产服务器版本是1.5.x+1或者是+2,反正就是比开发环境高一点。因此,在桌面版的settings.py中添加了ALLOWED_HOSTS,但缺少hwjp请求的“带有说明注释的默认值”,因此我在生产服务器上也添加了它,并使用了正确的域名。
但是,我没有注意到生产服务器上的Django版本更高,settings.py中已经有了一个带有说明注释的默认值。它在我输入的位置下方,屏幕上看不到。当然,列表是空的。因此,我浪费了很多时间。

2
我也遇到了完全相同的有趣模式!只不过在我发现这个之后才变得有趣,谢谢。在那之前,它只是让人沮丧。 - binithb
在这一切中有所帮助的是为每个环境使用一个 local_settings.py,然后在 settings.py 中导入它。 - nicorellius
1
我喜欢做的是,使用一个settings/目录代替settings.py。在这个目录中,你可以为不同的环境拥有单独的.py文件,并且有一个base.py用于通用设置。生产相关的设置可以从基本设置中导入*,并覆盖他们需要覆盖的内容。此外,所需的__init__.py将该settings/目录转换为有效模块,可以首先从base.py中导入,然后尝试从local.py中导入(仅在本地存在)。这意味着您不需要手动指定本地设置。 - mephisto

6

我知道这是一个非常老的问题,但是也许我可以帮助其他人。如果你在将DEBUG设置为False之后出现500错误,你可以在命令行中运行manage.py runserver来查看任何不会出现在任何Web错误日志中的错误。


5

当我将DEBUG = FALSE时,我也遇到了同样的问题。以下是各个答案和帖子中综合的解决方案。

默认情况下,在settings.py中我们有ALLOWED_HOSTS = []。根据情况,以下是您可能需要在ALLOWED_HOSTS值中进行的更改以消除错误:

1:您的域名:

ALLOWED_HOSTS = ['www.example.com'] # Your domain name here

2:如果您还没有域名,那么您部署的服务器IP将会是一个极好的选择(这就是我的情况,非常有效):

ALLOWED_HOSTS = ['123.123.198.123'] # Enter your IP here

3:如果您正在本地服务器上进行测试,可以编辑您的settings.pysettings_local.py文件:

ALLOWED_HOSTS = ['localhost', '127.0.0.1']

4:您也可以在ALLOWED_HOSTS值中提供“*”,但由于安全原因,在生产环境中不建议这样做

ALLOWED_HOSTS = ['*'] # Not recommended in production environment

我也在我的博客上发布了详细的解决方案,你可能想参考一下。


3

我知道这篇文章很旧,但它今天仍然非常相关。

不管怎样 - 我在我的网站上所有页面中使用 DEBUG = False 时都遇到了500的问题。

在调试模式下,我没有得到任何回溯信息。

我必须检查我的站点中模板内的每个静态链接,并发现其中一个图片源路径前面有一个 / (斜杠)。{% static ... %}。 在 DEBUG = False 下,这导致了500错误,但在Debug = True模式下却完全正常而无错误。非常烦人!请注意!由于一个斜杠,浪费了许多时间...


哇!感谢您节省时间。我有一个静态标签指向不存在的文件,并在“Debug=False”时抛出500错误。 - MjZac

3

当你在settings.py中设置了DEBUG = FalseALLOWED_HOSTS = ['127.0.0.1']之后,你可能需要运行python manage.py collectstatic。经过这两步操作,即使在DEBUG=False模式下,我的Web应用程序也可以在本地服务器上成功运行。

顺便说一下,这些设置在我的settings.py文件中。

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware', # what i added
    'django.middleware.common.CommonMiddleware', # and so on...
]

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

我猜测可能是whitenoise设置与collectstatic命令有关。

2

我有类似的问题,在我的情况下,是因为在body标签中有一个被注释掉的脚本。

<!--<script>  </script>-->

1
我认为这可能也与http服务器设置有关。我的服务器仍然无法使用,而ALLOWED_HOSTS一直存在。我可以在本地访问它(我使用gunicorn),但是当DEBUG=False时,无法通过域名访问。当我尝试使用域名时,会出现错误,因此我认为这是与nginx相关的问题。
以下是我的nginx配置文件:
server {
    listen   80;
    server_name localhost myproject.ca www.myproject.ca;
    root /var/web/myproject/deli_cms;

    # serve directly - analogous for static/staticfiles
    location /media/ {
        # if asset versioning is used
        if ($query_string) {
            expires max;
        }
    }
    location /admin/media/ {
        # this changes depending on your python version
        root /var/web/myproject/lib/python2.6/site-packages/django/contrib;
    }
    location /static/ {
    alias /var/web/myproject/deli_cms/static_root/;
    }

    location / {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_connect_timeout 10;
        proxy_read_timeout 10;
        proxy_pass http://localhost:8000/;
    }
    # what to serve if upstream is not available or crashes
    error_page 500 502 503 504 /media/50x.html;
}

我的gunicorn配置文件如下: #!/bin/bash cd /var/web/delicms_env/deli_cms/ source ../bin/activate exec gunicorn --workers=3 deli_cms.wsgi:application - user2868304
我的问题现在已经解决了,我之前使用的是gunicorn_django脚本,但它一直在给我发送弃用消息。我仍然不确定为什么它在本地工作正常,没有改变我的nginx配置,只是将旧脚本更改为使用gunicorn并使用wsgi:application模块,现在它又可以正常工作了。在此之前,Gunicorn也会抛出一些弃用消息,但与我的问题无关。 - user2868304

1
这可能会帮助其他人,在我的情况下,问题出在缺少网站图标。

1

有点晚了,可能会有很多问题,但我遇到过类似的问题,结果发现我在HTML注释中使用了{% %}特殊字符...

<!-- <img src="{% static "my_app/myexample.jpg" %}" alt="My image"/> -->

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接