Django 设置DEBUG=False会导致500错误
一旦我更改Django 设置DEBUG=False会导致500错误,django,settings,django-1.5,Django,Settings,Django 1.5,一旦我更改DEBUG=False,我的站点将生成500(使用wsgi&manage.py runserver),Apache错误日志中没有错误信息,当我将DEBUG更改为True时,它将正常运行 我正在使用Django1.5和Python2.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 "-
DEBUG=False
,我的站点将生成500(使用wsgi&manage.py runserver),Apache错误日志中没有错误信息,当我将DEBUG
更改为True
时,它将正常运行
我正在使用Django1.5和Python2.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',
)
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']
或['*']
以进行快速测试。对,在Django 1.5中,如果DEBUG=False
,则配置允许的\u主机,添加不带端口号的域。例如:
ALLOWED_HOSTS = ['localhost']
你还必须检查你的网址到处都是。当
DEBUG
设置为False
时,所有不带尾随/
的URL都被视为bug,这与使用DEBUG=True
时不同,在这种情况下,Django将在缺少/
的任何地方追加它。因此,简而言之,确保所有链接都以斜杠结尾。我有一个有趣的故事给大家听。到达此页面后,我说“Eureka!我被保存了。这一定是我的问题。”因此我在setting.py中插入了所需的允许的\u主机
列表,然后。。。没有什么。同样的老错误。不,这不是因为缺少404.html文件
所以有两天我忙于胡思乱想,比如说它与服务静态文件有关(要知道我是一个noob,noob不知道他们在做什么)
那是什么?现在是主持人先生,我们得到了一个有用的提示。我的开发Django版本是1.5.something,而我的生产服务器版本是1.5.something+1。。。或者加2。无论什么因此,在我将ALLOWED_HOSTS
添加到settings.py的桌面版本后,我在具有适当域的生产服务器上也做了同样的操作,该版本缺少hwjp所要求的“settings.py中的默认值,可能带有解释性注释”
但我没有注意到,在具有更高版本Django的生产服务器上,settings.py中有一个默认值,并带有解释性注释。它远远低于我进入的位置,在监视器上看不见。当然,这个列表是空的。因此我浪费了时间。我想这也可能是http服务器设置。我的还是坏掉了,一直都是东道主。我可以在本地访问它(我使用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;
}
值得一提的是,我只在一些页面上得到了500分,其中
DEBUG=False
。使用pdb跟踪异常时发现缺少资产(我怀疑{%static…%}
模板标记是500的罪魁祸首。我知道这是一个老问题,但当DEBUG=False时,我也遇到了一个500错误。几个小时后,我意识到我忘记了用斜杠结束base.html中的一些链接。我遇到了同样的问题,当时我做了DEBUG=False
。下面是一个综合解决方案在上面的答案和其他帖子中都有类似的描述
默认情况下,在settings.py中有ALLOWED_HOSTS=[]
。以下是您必须根据场景在ALLOWED_HOSTS
值中进行的可能更改,以消除错误:
1:您的域名:
ALLOWED_HOSTS = ['www.example.com'] # Your domain name here
2:如果你还没有域名,你部署的服务器IP(这是我的情况,工作起来很有魅力):
3:如果您在本地服务器上进行测试,您可以编辑您的settings.py
或settings\u local.py
,如下所示:
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
4:您也可以在允许的\u HOSTS
值中提供“*”,但由于安全原因,不建议在生产环境中使用它的:
ALLOWED_HOSTS = ['*'] # Not recommended in production environment
我还发布了一个详细的解决方案,您可以参考。在我的例子中,阅读第三方应用程序的文档正确地保存了我 罪犯?django_压缩机 我有
{% load compress %}
{% compress css %}
... css files linked here ..
{% endcompress %}
DEBUG=True
总是给我500。要修复它,我需要在设置中添加一行代码来运行它
COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False)
这是老生常谈,我的问题最终与问题有关,但不是针对OP,但我的解决方案适用于任何尝试上述方法无效的其他人
我在Django的一个修改版本中设置了一个用于缩小CSS和JS文件的设置,这些文件只在调试关闭时运行。我的服务器没有安装CSS缩小器并抛出了错误。如果您使用Django Mako Plus,这可能是您的问题。允许的\u主机不是唯一的问题,对我来说,我必须制作一个404.html并将其置于基本级别o对于我的模板(不是应用程序级)-同样,你可以创建一个404视图并添加一个404handler url,但我认为这是可选的。404.html修复了它 在mainproject.url中
handler404 = 'app.views.custom_404'
应用程序内视图
def custom_404(request):
return render(request, '404.html', {}, status=404)
然后制作一个templates/404.html模板
从另一个S/O帖子上得到的,我找不到
编辑
另外,当我使用whitenoise服务资产时,我也会遇到500个错误。在我的一生中,我都无法理解这一点,错误是因为whitenoise无法找到我也找不到的资产而产生的ValueError,现在必须使用默认的django服务需要注意的一点是,如果数组中没有,那么所有后续允许的主机都被忽略了
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版本1.8.4补充了主要答案
在开发和生产之间切换时,在
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:
...
我知道这很晚了,但我在我的
if socket.gethostname().endswith(".local"): # True in your local computer
DEBUG = True
ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
else:
...
# 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',
},
}
}
<!-- <img src="{% static "my_app/myexample.jpg" %}" alt="My image"/> -->
<!--<script> </script>-->
python manage.py collectstatic
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
{% 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 %}
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
STATICFILES_STORAGE = django.contrib.staticfiles.storage.StaticFilesStorage
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
django.urls.exceptions.NoReverseMatch: Reverse for 'home' not found.
or...
django.urls.exceptions.NoReverseMatch: Reverse for 'about' not found.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # what i added
'django.middleware.common.CommonMiddleware', # and so on...
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'