首页 文章

设置DEBUG = False会导致500错误

提问于
浏览
270

一旦我更改 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',
)

24 回答

  • 1

    Django 1.5引入了出于安全原因所需的allowed hosts setting . 使用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']['*'] ,以进行快速测试,but don't use ['*'] for production .

  • 0

    我知道这已经晚了但是我最终在这里搜索了我的错误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',
            },
        }
    }
    
  • 21

    在我的情况下,阅读第三方应用程序的文档正确地保存了我 .

    罪魁祸首? django_compressor

    我有

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

    DEBUG = True 总是给我500.要解决它,我需要在我的设置中使用一行来让它运行

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

    对,在Django 1.5中如果DEBUG = False,配置ALLOWED_HOSTS,添加没有端口号的域 . 例:

    ALLOWED_HOSTS = ['localhost']
    
  • 13

    您还必须在整个地方检查您的网址 . 当 DEBUG 设置为 False 时,所有不带尾随 / 的URL都会被视为错误,这与您拥有 DEBUG = True 不同,在这种情况下,Django会在缺少的地方附加 / . 因此,简而言之,确保所有链接都以斜线结尾 .

  • -5

    我刚刚在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 来修复它 .

  • 1

    对于它的 Value - 我只在某些页面上获得了500的 DEBUG = False . 用pdb追溯异常显示缺少资产(我怀疑 {% static ... %} 模板标签是500的罪魁祸首 .

  • 0

    我有一个热闹的故事 . 到达此页面后,我说"Eureka! I'm saved. That MUST be my problem."所以我在setting.py中插入了所需的 ALLOWED_HOSTS 列表并且......没有 . 相同的旧500错误 . 不,它不是因为缺少404.html文件 .

    因此,在2天的时间里,我忙于疯狂的理论,例如它与服务静态文件有关(理解我是菜鸟,而且新手不知道他们在做什么) .

    那是什么?现在是主持人,我们得到了一个有用的提示 . 虽然我的开发Django是版本1.5.something,我的 生产环境 服务器版本是1.5.something 1 ...或者可能加2.无论如何 . 因此,在我将 ALLOWED_HOSTS 添加到桌面版本的settings.py之后,缺少hwjp请求的内容--- "default value in settings.py, perhaps with an explanatory comment" ---我在 生产环境 服务器上使用适当的域做了同样的事情 .

    但我没注意到在 生产环境 服务器上使用更高版本的Django,在settings.py中有一个带有解释性注释的默认值 . 它远远低于我进入的地方,在显示器上看不到 . 当然,这份清单是空的 . 因此我浪费时间 .

  • 10

    当我做 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 值中提供'*',但由于安全原因,它的 not recommended in the production environment

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

    我还在blog上发布了一个您可能想要参考的详细解决方案 .

  • 6

    Complementing the main answer
    在开发和 生产环境 之间切换时,更改 settings.py 中的ALLOWED_HOSTS和DEBUG全局常量很烦人 . 我正在使用此代码自动设置这些设置:

    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:
        ...
    
  • 6

    ALLOWED_HOSTS不是唯一的问题,对我来说,我必须制作一个404.html并将其放在我的模板的基础级别(而不是应用级别) - 此外,你可以制作一个404查看并添加404handler网址,但我认为这是可选的 . 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帖子得到这个

    EDIT

    此外,当我使用whitenoise提供资产时,我收到500个错误 . 无法想象我的生活,错误是来自whitenoise的ValueError无法找到我也找不到的资产,不得不使用默认的django现在服务

  • 0

    我正在搜索和测试更多关于这个问题,我意识到settings.py中指定的静态文件可能是导致这种情况的原因,所以我们需要运行这个命令

    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')
    
  • 2

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

  • 0

    我认为它也可能是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;
    }
    
  • 5

    我有类似的问题,在我的情况下,它是由body标签内的一个注释脚本引起的 .

    <!--<script>  </script>-->
    
  • 3

    我遇到了这个问题 . 事实证明,我在模板中包含了 static 模板标签,这是一个不再存在的文件 . 在日志中查看我的问题 .

    我想这只是造成这种错误的众多可能原因之一 .

    故事的道德:始终记录错误并始终检查日志 .

  • 1

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

    我的django应用程序中有一些问题 . 我删除了该行
    STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' 我是从heroku的文档中找到的 .

    我还必须在django应用程序的根目录中添加额外的目录(感谢another SO answerstatic 作为 myapp/static ,即使我没有使用它 . 然后在运行服务器之前运行命令 python manage.py collectstatic 解决了问题 . 最后,它开始工作正常 .

  • 10

    我知道这是一个老问题,但是当DEBUG = False时我也得到500错误 . 几个小时后,我意识到我忘了用一个尾部斜杠结束我的base.html中的一些链接 .

  • 0

    这是旧的,我的问题最终与问题有关,但不是与OP相关,但我的解决方案是针对其他尝试上述操作的人无济于事 .

    我在Django的修改版本中设置了一个设置来缩小仅在DEBUG关闭时运行的CSS和JS文件 . 我的服务器没有安装CSS minifier并抛出错误 . 如果您使用的是Django-Mako-Plus,这可能是您的问题 .

  • 29

    需要注意的一件小事,如果数组中有None,则忽略所有后续允许的主机 .

    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

  • 1

    派对有点晚了,当然可能会出现大量问题,但我遇到了类似的问题,结果发现我的html评论中有{%}}个特殊字符...

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

    我有一个视图在debug = false中抛出500错误但在debug = true中工作 . 对于任何正在获得此类事情并且允许主机不是问题的人,我通过更新指向错误位置的模板的静态标记来修复我的视图 .

    所以我建议只检查链接和标签在所使用的任何模板中都是密不透风的,也许某些东西会在调试中滑过网络但在 生产环境 中会出错 .

  • 400

    当DEBUG = False时,我发现500错误的另一个原因 . 我使用Django compressor 实用程序,我们的前端工程师在Django模板的 compress css 块中添加了对字体文件的引用 . 像这样:

    {% 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 %}
    

    解决方案是将链接移动到 endcompress 行下面的 ttf 文件 .

  • 5

    如果要允许所有主机 . 使用ALLOWED_HOSTS = ['',]而不是ALLOWED_HOSTS = ['']

相关问题