当模板调试设置为 False 时,Django 上的服务器错误(500)?

Posted

技术标签:

【中文标题】当模板调试设置为 False 时,Django 上的服务器错误(500)?【英文标题】:Server Error (500) on Django when template debug is set to False? 【发布时间】:2013-06-03 15:22:45 【问题描述】:

当我在 Django 中设置 DEBUG = False 时,我看到了 Django 500 Error。我正在使用Django 1.5 and Python 2.7。我还在我的模板中包含了ALLOWED_HOSTS。这是我的完整设置.py:

# Django settings for genalytics project.
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
import djcelery
import os
__file__ = os.getcwd()

ROOT_PATH = os.path.dirname(__file__)

djcelery.setup_loader()

#New in Django 1.5
ALLOWED_HOSTS = ['localhost', '127.0.0.1:8000'] 

DEBUG = False
TEMPLATE_DEBUG = DEBUG

ADMINS = (
     ('sachit', 'sachit.adhikari@zurelsoft.com')
)


BROKER_TRANSPORT = "sqlalchemy"
BROKER_URL = "sqla+mysql://root:password@localhost/galaxy"


MANAGERS = ADMINS

DATABASES = 
    'default': 
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'galaxy',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': 'password',                  # 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.
                    

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

# 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: "/var/www/example.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
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: "/var/www/example.com/static/"
STATIC_ROOT = ''

STATIC_URL = '/static/'

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"

AUTHENTICATION_BACKENDS = (
    'fileupload.backend.AuthBackend',
 )

# Additional locations of static files
STATICFILES_DIRS = (
)
# 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 = '$ec_7m$05ddhhc_cy(j-i^%70ochjmx*$0_o!$u1q9rkkd(ai$'

# 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',
)

TEMPLATE_CONTEXT_PROCESSORS += (
    'django.core.context_processors.request',
    'django.contrib.messages.context_processors.messages'
)

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',
    'fileupload.middleware.AutoLogout'
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'

#Pagination Setting
ENDLESS_PAGINATION_PREVIOUS_LABEL = '<'
ENDLESS_PAGINATION_NEXT_LABEL = '>'

ENDLESS_PAGINATION_FIRST_LABEL = '|<'
ENDLESS_PAGINATION_LAST_LABEL = '>|'

ROOT_URLCONF = 'genalytics.urls'

SESSION_COOKIE_AGE = 30 * 60


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

TEMPLATE_DIRS = (
            os.path.join(ROOT_PATH, 'fileupload/templates'),


)

DESTINATION = '/home/zurelsoft/files/'

AUTO_LOGOUT_DELAY = 30

AUTH_USER_MODEL = 'fileupload.user'

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'fileupload',
    'django.contrib.admin',
    'endless_pagination',
    'djcelery',
    'endless_pagination'
)



# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = 
    'version': 1,
    'disable_existing_loggers': False,
    'filters': 
        'require_debug_false': 
            '()': 'django.utils.log.RequireDebugFalse'
        
    ,

    'handlers': 
        'mail_admins': 
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        
    ,
    'loggers': 
        'django.request': 
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        ,
    

怎么了?

按照 Ryu_hayabusa 的建议更新了日志记录,我在控制台中收到此错误:

Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.commands.runserver.Command object at 0x22e08d0>>
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 114, in inner_run
    ipv6=self.use_ipv6, threading=threading)
  File "/usr/local/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 193, in run
    httpd.serve_forever()
  File "/usr/lib/python2.7/SocketServer.py", line 235, in serve_forever
    r, w, e = _eintr_retry(select.select, [self], [], [],
AttributeError: 'NoneType' object has no attribute 'select'

【问题讨论】:

查看您的网络服务器错误日志。我们应该怎么知道?? 日志存储在哪里?我没有收到任何关于我的邮件地址错误的消息。 你使用什么网络容器?独角兽? uwsgi?其中每一个都有关于其访问和错误日​​志的设置。这就是你应该寻找的地方。 我正在使用 Django inbuild 开发服务器来测试 debug=false。 尝试根据settings.DEBUG 为每个条件搜索您的代码并删除/切换其逻辑,可能存在隐藏问题。还尝试将 DEBUGTEMPLATE_DEBUG 值分开,这会导致您的问题。 【参考方案1】:

使用下面的LOGGING设置,那么你应该可以在控制台看到错误。

LOGGING = 
    'version': 1,
    'disable_existing_loggers': False,
    'filters': 
        'require_debug_false': 
            '()': 'django.utils.log.RequireDebugFalse'
        
    ,

    'handlers': 
        'mail_admins': 
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        ,
        'console':
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        ,
    ,
    'loggers': 
        'django.request': 
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        ,
    

记得设置DEBUG = False

【讨论】:

控制台出错。我正在更新我的问题,包括错误。 对不起,我帮不上忙,你可以试试 1.暂时将你的数据库设置为 sqlite,看看问题是否仍然存在。 2. 检查 urls.py 是否有类似 ***.com/questions/8171955/… 的错误。 您在遵循@Ryu_hayabusa 的配置记录器建议后发布的错误是导致错误 500(这是内部服务器错误)的实际错误。【参考方案2】:

对于 django v 1.5+,在你的 settings.py 文件中,进行配置 ALLOWED_HOSTS = ['*'] 如果你想快速修复

如果您真的要进行生产(并且担心安全性),请将允许的主机名放入 ALLOWED_HOSTS

此 SO 链接有更多信息

Setting DEBUG = False causes 500 Error

【讨论】:

【参考方案3】:

转到 django 管理门户。 单击站点表并将 example.com 站点编辑为您的域名。 它会起作用的。

【讨论】:

【参考方案4】:

在关闭DEBUG 后,我也收到了500 Internal Server 错误。发生这种情况的另一个原因是,如果您在相对静态路径的开头有一个额外的 /。所以替换:

<link rel="stylesheet" href="% static '/css/somecustom.css' %">

<link rel="stylesheet" href="% static 'css/somecustom.css' %">

即在您的模板文件中搜索并替换 % static '/% static '

要进一步了解这一点,您可以阅读 Django 的 ManifestStaticFilesStorage 后端的缓存行为。

【讨论】:

以上是关于当模板调试设置为 False 时,Django 上的服务器错误(500)?的主要内容,如果未能解决你的问题,请参考以下文章

为啥当 Debug 设置为 False 时,Django 会为静态媒体生成 HTTP 500 错误?

为什么只有当Debug = False并且db在Heroku上设置为生产数据库时,django才会因服务器500而失败?

调试模式打开时的 Django 和静态文件

Django本地调试时模拟服务器使用url方式访问静态文件(不建议使用)

Django设置 DEBUG=False后静态文件无法加载解决

当 DEBUG = False 时 Django 转义 javascript