设置DEBUG = false会导致错误500(Setting DEBUG = False caus

2019-07-20 17:24发布

有一次,我改变DEBUG = False ,我的网站会产生500(使用WSGI和manage.py runserver命令),并且在Apache的错误日志中没有错误信息,当我改变它会正常运行debugTrue

我使用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',
)

Answer 1:

Django的1.5引入了允许的主机设置是出于安全的需要。 在Django 1.5创建的设置文件有这个新的部分,你需要添加:

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.9/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

在此添加喜欢你的主机['www.beta800.net']['*']一个快速测试, 但不要用['*']进行生产 。



Answer 2:

我知道这是晚了,但我在这里结束了与我的错误500与搜索DEBUG=False ,在我的情况下,它也变成是ALLOWED_HOSTS ,但我是用os.environ.get('variable')来填充主人,我没有注意到这一点,直到我启用了日志记录,可以记录所有的错误与下面文件,当它甚至会记录DEBUG=False

# settings.py
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'mysite.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers':['file'],
            'propagate': True,
            'level':'DEBUG',
        },
        'MYAPP': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    }
}


Answer 3:

在我的情况下,第三方应用程序的阅读文档正确救了我。

罪魁祸首? django_compressor

我有

{% load compress %}
{% compress css %}
 ... css files linked here ..
{% endcompress %}

DEBUG = True总是给我500.要解决它,我需要在我的设置一条线,让它运行

COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False)


Answer 4:

我在Django 2.0刚刚遇到了同样的问题。 我能够通过设置来弄清楚这个问题DEBUG_PROPAGATE_EXCEPTIONS = True 。 在这里看到: https://docs.djangoproject.com/en/2.0/ref/settings/#debug-propagate-exceptions

在我的情况下,错误是ValueError: Missing staticfiles manifest entry for 'admin/css/base.css' 。 我固定,通过本地运行python manage.py collectstatic



Answer 5:

右,在Django 1.5如果DEBUG = FALSE,配置ALLOWED_HOSTS,加入域而不的端口号。 例:

ALLOWED_HOSTS = ['localhost']


Answer 6:

您还必须检查你的网址,所有的地方。 当DEBUG被设置为False ,无拖尾的所有URL /被视为一个错误,当你有不同DEBUG = True ,在这种情况下,Django会追加/随处可见它丢失了。 因此,简而言之,确保各个环节有一个斜线结束随处可见。



Answer 7:

我对所有的爆笑故事。 达到这一页后,我说:“找到了!我得救了。那一定是我的问题。” 所以我插入所需ALLOWED_HOSTS在setting.py和列表...没什么。 老一套的500错误。 不,这不是因为缺乏404.html文件。

所以,2天,我整天忙于疯狂的理论,比如,它有一些东西需要与提供静态文件(明白,我一个小白菜鸟和不知道他们在做什么)。

那又是什么? 现在是主持人先生,我们到了一个有用的技巧。 而我发展Django是版本1.5.something,我的生产服务器版本1.5.something + 1 ...也许加2不管。 所以在我加入ALLOWED_HOSTSsettings.py的桌面版本,它缺少请求什么hwjp ---一个“settings.py中的默认值,也许说明注释” ---我没有在生产服务器上的相同与它正确的域。

但是,我没有注意到,在Django的更高版本有一个与说明性注释settings.py中的默认值在生产服务器上。 这是远远低于,我做了我的进入,淡出人们的视线在监视器上。 当然还有列表是空的。 因此,我的时间浪费。



Answer 8:

对于它的价值-我得到了500 DEBUG = False上只有一些网页。 追溯与PDB异常透露了一个缺失资源(我怀疑{% static ... %}模板标签是为500的罪魁祸首。



Answer 9:

我面临同样的问题,当我做了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

我也贴在我一个详细的解决方案博客 ,你可能希望参考。



Answer 10:

补充的主要答案
这是恼人的改变ALLOWED_HOSTS和调试全局常量settings.py开发和生产之间切换时。 我使用此代码自动设置这些设置:

import socket

if socket.gethostname() == "server_name":
    DEBUG = False
    ALLOWED_HOSTS = [".your_domain_name.com",]
    ...
else:
    DEBUG = True
    ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
    ...

如果你使用的MacOS,你可以写一个更通用的代码:

if socket.gethostname().endswith(".local"): # True in your local computer
    DEBUG = True
    ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
else:
    ...


Answer 11:

ALLOWED_HOSTS是不是唯一的问题,对我来说我不得不做出一个404.html,并把它放在我的模板(未应用级)的基本水平 - 而且,你可以做一个404视图,并添加404handler URL,但我认为是可选的。 404.html固定它

在mainproject.urls

handler404 = 'app.views.custom_404'

在app.views

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

然后做一个模板/ 404.html模板

得到这个从另一个S / O后,我无法找到它

编辑

还有,我得到500错误,当我成为资产白噪声。 无法找出答案,我的生活,从错误不能够找到一个资产,我也找不到白噪声是ValueError异常,不得不去使用默认的Django服务现在



Answer 12:

我正在寻找和测试更多关于这个问题,我意识到,在settings.py指定的静态文件direcotiries可以是这样的原因,所以拳头,我们需要运行这个命令

python manage.py collecstatic

settings.py中的代码应该是这个样子:

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')


Answer 13:

我知道,这是一个超级老问题,但也许我可以帮助一些其他人。 如果要设置DEBUG后,得到了500错误=假,你总是可以运行在命令行manage.py runserver命令看到,不会出现在任何网页错误日志的任何错误。



Answer 14:

我想这也可能是http服务器设置。 煤矿仍然是断开的,不得不ALLOWED_HOSTS的整个时间。 我可以(我用gunicorn),但不通过域名本地访问它时,DEBUG =假。 当我尝试使用该域名,然后它给我的错误,所以让我觉得它是一个nginx的相关问题。

这里是我的nginx的文件CONF:

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;
}


Answer 15:

我有类似的问题,在我的情况下,它是由具有body标签内的评论脚本引起的。

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


Answer 16:

我就遇到了这个问题。 原来我包括模板,使用static模板标签,这并不存在了一个文件。 在日志中一看给我的问题。

我想这仅仅是对这种错误的许多可能的原因之一。

这个故事的寓意:始终记录错误,并经常检查日志。



Answer 17:

由于@squarebear,在日志文件中,我发现了错误: ValueError: The file 'myapp/styles.css' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage ...>

我曾在我的Django应用程序的一些问题。 我删除行
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'这是我从Heroku的文档中。

我也不得不(感谢添加额外的目录另一SO接听 ) static在Django应用程序的根目录myapp/static ,即使我不使用它。 然后运行命令python manage.py collectstatic运行服务器之前解决了这个问题。 最后,它开始工作的罚款。



Answer 18:

我知道这是一个老问题,但我也得到一个500错误,当DEBUG =假。 几个小时后,我才意识到我已经忘了来结束一些链接在我base.html文件以斜杠。



Answer 19:

这是旧的,我的问题结束了相关的问题,但不是为OP,但我的解决方案是为别人谁试图上述无济于事。

我曾在Django的修改版本的设置来缩小CSS和JS文件,只有当DEBUG被关运行。 我的服务器没有安装的CSS minifier,扔了错误。 如果您正在使用Django的马可加,这可能是您的问题。



Answer 20:

一个小一点要注意,如果数组有没有在里面,那么所有后续允许的主机被忽略。

ALLOWED_HOSTS = [
    "localhost",
    None,
    'example.com', # First DNS alias (set up in the app)
    #'www.example.com', # Second DNS alias (set up in the app)
]

Django version 1.8.4



Answer 21:

有点迟到了,和关闭过程可能存在的问题进行了军团,但是我也有过类似的问题,事实证明,我有{%}我的HTML句话里的特殊字符...

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


Answer 22:

我在调试=假扔了一个500错误,但在调试工作=真正的一个观点。 对于任何人谁获得这种事情和允许的主机是没有问题的,我通过更新模板的这是指向错误的位置静态标签固定我的看法。

所以,我建议只检查链接和标签中使用任何模板,也许某些事情漏网之鱼在调试的网,但在生产中得到错误密闭。



Answer 23:

我发现500错误时,DEBUG =假的又一原因。 我用的是Django的compressor实用程序和我们的前端工程师加入引用字体的内部文件compress css在Django模板块。 像这样:

{% compress css %}
    <link href="{% static "css/bootstrap.css" %}" rel="stylesheet">
    <link href="{% static "css/bootstrap-spinedit.css" %}" rel="stylesheet">
    <link href="{% static "djangular/css/styles.css" %}" rel="stylesheet">
    <link href="{% static "fonts/fontawesome-webfont.ttf" %}" rel="stylesheet">
{% endcompress %}

解决的办法是链接移动到ttf以下文件endcompress线。



Answer 24:

如果你要允许所有主机。 使用ALLOWED_HOSTS = [ '*',]代替ALLOWED_HOSTS = [ '*']



文章来源: Setting DEBUG = False causes 500 Error