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

11

当我在Django中设置DEBUG = False时,我遇到了Django 500错误。我正在使用Django 1.5和Python 2.7。我还在我的模板中包含了ALLOWED_HOSTS。这是我的完整settings.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'

请查看您的Web服务器错误日志。我们怎么知道呢? - Jingo
日志存储在哪里?我没有收到任何关于错误的消息,也没有通过电子邮件地址接收到任何消息。 - pynovice
你使用什么Web容器?gunicorn?uwsgi?每个容器都有关于访问和错误日志的设置。那就是你应该查看的地方。 - rantanplan
我正在使用Django内置的开发服务器来测试debug=false。 - pynovice
尝试搜索您的代码以查找基于settings.DEBUG的每个条件,并删除/切换其逻辑,可能存在隐藏问题。还要尝试分离DEBUGTEMPLATE_DEBUG值,看看哪一个导致了您的问题。 - yedpodtrzitko
我在代码中的任何部分都没有提及settings.DEBUG。 - pynovice
4个回答

7

使用以下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


在控制台中出现错误。我正在更新我的问题,包括错误信息。 - pynovice
抱歉,我在这方面帮不上太多忙,以下是你可以尝试的方法:
  1. 将数据库暂时设置为sqlite,并查看问题是否仍然存在。
  2. 检查urls.py文件是否存在类似于http://stackoverflow.com/questions/8171955/django-strange-behavior-using-static-files的错误。
- Ryu_hayabusa
在按照 @Ryu_hayabusa 的建议配置记录器后,您发布的错误是实际导致错误 500(即内部服务器错误)的错误。 - Baschdl

4

对于 django v 1.5+ 版本,在 settings.py 文件中配置 ALLOWED_HOSTS = ['*'],如果您想要快速解决问题。

如果您真的要上线(并且关心安全性),请将允许的主机名放在 ALLOWED_HOSTS 中。

此 SO 链接提供了更多信息。

设置 DEBUG = False 导致 500 错误


1
在关闭DEBUG后,我遇到了500内部服务器错误。另一个可能的原因是在相对静态路径的开头有额外的/。所以请将其替换为:
<link rel="stylesheet" href="{% static '/css/somecustom.css' %}">

使用

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

即在模板文件中使用 {% static '/ 进行搜索和替换为 {% static '

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


0

进入Django管理门户。
点击站点表并将example.com网站编辑为您的域名。
它会起作用的。


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