Once I change the DEBUG = False
, my site will generate 500 (using wsgi & manage.py runserver), and there is no error info in Apache error log and it will run normally when I change debug
to True
.
一旦我更改DEBUG = False,我的站点将生成500个(使用wsgi & manage)。在Apache错误日志中没有错误信息,当我将调试更改为True时,它将正常运行。
I'm using Django 1.5 & Python 2.7.3 here is Apache access log and without any log in apache error log
我使用的是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"
Here is my settings file:
这是我的设置文件:
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
395
Django 1.5 introduced the allowed hosts setting that is required for security reasons. A settings file created with Django 1.5 has this new section which you need to add:
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 = []
Add your host here like ['www.beta800.net']
or ['*']
for a quick test, but don't use ['*']
for production.
在这里添加您的主机,如['www.beta800.net']或['*']进行快速测试,但不要将['*']用于生产。
#2
22
In my case, reading docs of third party apps properly saved me.
在我的案例中,阅读第三方应用程序的文档能够正确地拯救我。
The culprit? django_compressor
罪魁祸首吗?django_compressor
I had
我有
{% load compress %}
{% compress css %}
... css files linked here ..
{% endcompress %}
DEBUG = True
always gave me 500. To fix it, I needed a line in my settings to get it running
DEBUG = True总是给我500。为了修复它,我需要在我的设置中使用一行代码来运行它
COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False)
#3
21
I know this is late but I ended up here with a search for my error 500 with DEBUG=False
, in my case it did turn out to be the ALLOWED_HOSTS
but I was using os.environ.get('variable')
to populate the hosts, I did not notice this until I enabled logging, you can log all errors to file with the below and it will log even when DEBUG=False
:
我知道这是晚但我最终在这里寻找我的错误500 DEBUG = False,就我而言它确实是ALLOWED_HOSTS但我用os.environ.get(变量)来填充主机,我才注意到这个启用日志记录,可以用下面的所有错误日志文件并将日志即使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',
},
}
}
#4
12
Right, in Django 1.5 if DEBUG = False, configure ALLOWED_HOSTS, adding domains without the port number. example:
在Django 1.5中,如果DEBUG = False,配置ALLOWED_HOSTS,添加没有端口号的域。例子:
ALLOWED_HOSTS = ['localhost']
#5
9
You must also check your URLs all over the place. When the DEBUG
is set to False
, all URLs without trailing /
are treated as a bug, unlike when you have DEBUG = True
, in which case Django will append /
everywhere it is missing. So, in short, make sure all links end with a slash EVERYWHERE.
您还必须检查您的url各地。当调试被设置为False时,所有的url都被当作一个bug,不像你有DEBUG = True,在这种情况下,Django将附加/到处都没有。因此,简而言之,确保所有链接都以斜线结尾。
#6
6
I have a hilarious story for all. After reaching this page I said "Eureka! I'm saved. That MUST be my problem." So I inserted the required ALLOWED_HOSTS
list in setting.py and... nothing. Same old 500 error. And no, it wasn't for lack of a 404.html file.
我有一个有趣的故事。到了这一页后,我说:“找到了!”我得救了。那一定是我的问题。因此我在设置中插入了所需的ALLOWED_HOSTS列表。py和…什么都没有。老500错误。不,不是因为缺少404页面。html文件。
So for 2 days I busied myself with wild theories, such as that it had something to do with serving static files (understand that I am a noob and noobs don't know what they're doing).
因此,我花了两天时间研究一些疯狂的理论,比如它与提供静态文件有关(要知道我是noob, noobs不知道他们在做什么)。
So what was it? It is now Mr. Moderator that we come to a useful tip. Whereas my development Django is version 1.5.something, my production server version is 1.5.something+1... or maybe plus 2. Whatever. And so after I added the ALLOWED_HOSTS
to the desktop version of settings.py, which lacked what hwjp requested--- a "default value in settings.py, perhaps with an explanatory comment"--- I did the same on the production server with the proper domain for it.
那么是什么呢?现在是主持人先生,我们得到了一个有用的建议。而我的开发Django是1.5版。我的产品服务器版本是1.5.something+1…或者+ 2。无论什么。在我将ALLOWED_HOSTS添加到设置的桌面版本之后。py缺少hwjp所要求的——“设置中的默认值”。py,也许有一个解释性的注释“---我在生产服务器上做了相同的事情。
But I failed to notice that on the production server with the later version of Django there WAS a default value in settings.py with an explanatory comment. It was well below where I made my entry, out of sight on the monitor. And of course the list was empty. Hence my waste of time.
但是我没有注意到,在Django的后期版本的生产服务器上,设置中有一个默认值。带着解释性的评论。它就在我进去的地方下面,在监视器上看不见。当然名单是空的。因此我浪费时间。
#7
5
I faced the same problem when I did DEBUG = FALSE
. Here is a consolidated solution as scattered in answers above and other posts.
我在做DEBUG = FALSE时遇到了同样的问题。这里有一个综合的解决方案,分散在上面的答案和其他文章中。
By default, in settings.py we have ALLOWED_HOSTS = []
. Here are possible changes you will have to make in ALLOWED_HOSTS
value as per scenario to get rid of the error:
默认情况下,在设置。我们有ALLOWED_HOSTS =[]。为了消除错误,您可能需要根据场景在ALLOWED_HOSTS值中进行更改:
1: Your domain name:
1:你的域名:
ALLOWED_HOSTS = ['www.example.com'] # Your domain name here
2: Your deployed server IP if you don't have domain name yet (which was my case and worked like a charm):
2:如果你还没有域名,你部署的服务器IP(这是我的情况,而且工作起来很有魅力):
ALLOWED_HOSTS = ['123.123.198.123'] # Enter your IP here
3: If you are testing on local server, you can edit your settings.py
or settings_local.py
as:
3:如果您正在本地服务器上测试,您可以编辑您的设置。py或settings_local。py:
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
4: You can also provide '*' in the ALLOWED_HOSTS
value but its not recommended in the production environment due to security reasons:
4:您还可以在ALLOWED_HOSTS值中提供“*”,但出于安全原因,不建议在生产环境中提供:
ALLOWED_HOSTS = ['*'] # Not recommended in production environment
I have also posted a detailed solution on my blog which you may want to refer.
我还在我的博客上发布了一个详细的解决方案,你可以参考一下。
#8
5
For what it's worth - I was getting a 500 with DEBUG = False
on some pages only. Tracing back the exception with pdb revealed a missing asset (I suspect the {% static ... %}
template tag was the culprit for the 500.
值得注意的是,我只在某些页面上得到了500个DEBUG = False。用pdb跟踪异常发现了一个丢失的资产(我怀疑是{% static…%} template标签是500的罪魁祸首。
#9
5
I encountered the same issue just recently in Django 2.0. I was able to figure out the problem by setting DEBUG_PROPAGATE_EXCEPTIONS = True
. See here: https://docs.djangoproject.com/en/2.0/ref/settings/#debug-propagate-exceptions
我最近在Django 2.0中遇到了同样的问题。我可以通过设置debug_propagate_exception来解决这个问题= True。在这里看到的:https://docs.djangoproject.com/en/2.0/ref/settings/ # debug-propagate-exceptions
In my case, the error was ValueError: Missing staticfiles manifest entry for 'admin/css/base.css'
. I fixed that by locally running python manage.py collectstatic
.
在我的例子中,错误是ValueError:缺少“admin/css/base.css”的staticfiles清单条目。我通过本地运行python管理修复了这个问题。py collectstatic。
#10
5
Complementing the main answer
It is annoying to change the ALLOWED_HOSTS and DEBUG global constants in settings.py
when switching between development and production. I am using this code to set these setting automatically:
补充主要的答案,更改ALLOWED_HOSTS和调试设置中的全局常量非常烦人。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",]
...
If you use macOS you could write a more generic code:
如果您使用macOS,您可以编写更通用的代码:
if socket.gethostname().endswith(".local"): # True in your local computer
DEBUG = True
ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
else:
...
#11
4
ALLOWED_HOSTS is NOT the only issue, for me I had to make a 404.html and put it in the base level of my templates (not app level) - Also, you can make a 404 view and add a 404handler url but I think thats optional. 404.html fixed it
ALLOWED_HOSTS并不是唯一的问题,对我来说,我需要创建一个404。html并把它放在我的模板的基础层(不是应用程序层)——同样,你可以创建一个404视图并添加一个404handler url,但我认为这是可选的。404年。html固定它
in mainproject.urls
在mainproject.urls
handler404 = 'app.views.custom_404'
in app.views
在app.views
def custom_404(request):
return render(request, '404.html', {}, status=404)
then make a templates/404.html template
然后模板/ 404。html模板
got this from another S/O post that I cannot find it
从我找不到的另一个S/O帖子中得到这个。
EDIT
编辑
also, I get 500 errors when I serve assets with whitenoise. Could not figure that out for the life of me, error was ValueError from whitenoise not being able to find an asset that I also could not find, had to go with default django serving for now
另外,在使用whitenoise处理资产时,我将得到500个错误。我怎么也搞不清楚,错误是whitenoise的ValueError因为找不到我也找不到的资产,现在只能用django的默认值
#12
2
I know that this is a super old question, but maybe I could help some one else. If you are having a 500 error after setting DEBUG=False, you can always run the manage.py runserver in the command line to see any errors that wont appear in any web error logs.
我知道这是一个非常古老的问题,但也许我可以帮助别人。如果在设置DEBUG=False之后出现500个错误,则始终可以运行管理。在命令行中查看不会出现在任何web错误日志中的错误。
#13
2
I was searching and testing more about this issue and I realized that static files direcotiries specified in settings.py can be a cause of this, so fist, we need to run this command
我对这个问题进行了更多的搜索和测试,我意识到静态文件在设置中指定了direcotiries。py可能是原因之一,所以首先,我们需要运行这个命令
python manage.py collecstatic
in settings.py, the code should look something like this:
在设置。py,代码应该是这样的:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
#14
1
I think it could also be the http server settings. Mine is still broken and had ALLOWED_HOSTS the entire time. I can access it locally (i use gunicorn), but not via the domain name when DEBUG=False. when I try using the domain name it then gives me the error, so makes me think its a nginx related issue.
我认为它也可以是http服务器设置。我的仍然是坏的,并且一直允许主机运行。我可以在本地访问它(我使用gunicorn),但在DEBUG=False时不能通过域名访问它。当我尝试使用域名时,它会给我错误,所以我认为这是一个nginx相关的问题。
Here is my conf file for 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;
}
#15
1
I have the similar issue, in my case it was caused by having a Commented script inside the body tag.
我也遇到了类似的问题,在我的例子中,它是由body标记内的注释脚本引起的。
<!--<script> </script>-->
#16
1
I ran into this issue. Turns out I was including in the template, using the static
template tag, a file that did not exist anymore. A look in the logs showed me the problem.
我遇到了这个问题。原来我使用的是静态模板标签,一个不再存在的文件。看一下日志就知道问题出在哪儿了。
I guess this is just one of many possible reasons for this kind of error.
我想这只是造成这种错误的众多原因之一。
Moral of the story: always log errors and always check logs.
故事的寓意:总是记录错误,总是检查日志。
#17
1
Thanks to @squarebear, in the log file, I found the error: ValueError: The file 'myapp/styles.css' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage ...>
.
感谢@squarebear,在日志文件中,我发现了错误:ValueError:文件的myapp/样式。在< whitenoisee .storage中找不到css'。CompressedManifestStaticFilesStorage…>。
I had a few problems in my django app. I removed the lineSTATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
which I found from the heroku's documentation.
我的django应用程序有一些问题。我删除了STATICFILES_STORAGE = 'whitenoise.django。我从heroku的文档中找到的GzipManifestStaticFilesStorage。
I also had to add extra directory (thanks to another SO answer) static
in the root of django application as myapp/static
even though I wasn't using it. Then running the command python manage.py collectstatic
before running the server solved the problem. Finally, it started working fine.
我还必须在django应用程序的根中添加额外的目录(感谢另一个SO答案)静态作为myapp/static,尽管我没有使用它。然后运行命令python管理。在运行服务器之前,py collectstatic解决了这个问题。最后,它开始运行良好。
#18
0
I know this is an old question, but I was also getting a 500 error when DEBUG=False. After several hours, I realized I had forgot to end some of the links in my base.html with a trailing slash.
我知道这是个老问题,但是当DEBUG=False时,我也得到了500个错误。几个小时后,我意识到我忘记结束我基地的一些链接了。带有斜杠的html。
#19
0
This is old and my problem ended up being related to the problem but not for the OP but my solution is for anyone else who tried the above to no avail.
这是老问题,我的问题最终与问题有关,但不是针对OP,我的解决方案是针对任何尝试过上述方法的人。
I had a setting in a modified version of Django to minify CSS and JS files that only ran when DEBUG was off. My server did not have the CSS minifier installed and threw the error. If you are using Django-Mako-Plus, this might be your issue.
我在一个修改后的Django版本中设置了一个设置,用于缩小只有在调试关闭时才会运行的CSS和JS文件。如果您正在使用Django-Mako-Plus,这可能是您的问题。
#20
0
One small thing to note, If the array has None in it, then all the subsequent allowed hosts are ignored.
需要注意的一件小事是,如果数组中没有,则所有后续允许的主机将被忽略。
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
Django 1.8.4版本
#21
0
A bit late to the party, and off course there could be a legion of issues but I've had a similar issue and it turned out that I had {% %} special characters inside my html remark...
聚会有点晚了,当然会有很多问题,但我也遇到过类似的问题,结果发现我的html注释中有{%}特殊的字符……
<!-- <img src="{% static "my_app/myexample.jpg" %}" alt="My image"/> -->
#22
0
I had one view that threw a 500 error in debug=false but worked in debug=true. For anyone who is getting this kind of thing and Allowed Hosts is not the problem, I fixed my view by updating a template's static tag that was pointing to the wrong location.
我有一个视图在debug=false中抛出500个错误,但在debug=true中工作。对于任何得到这种东西并允许主机的人来说,都不是问题所在,我通过更新指向错误位置的模板的静态标记来修复我的视图。
So I'd suggest just checking links and tags are airtight in any templates used, maybe certain things slip through the net in debug but give errors in production.
因此,我建议在使用的任何模板中检查链接和标签都是密封的,也许在调试中某些东西会在网络中滑过,但是在生产中会出现错误。
#23
0
I found yet another cause of the 500 error when DEBUG=False. I use the Django compressor
utility and our front-end engineer added references to font files inside a compress css
block in a Django template. Like this:
在DEBUG=False时,我发现了另一个导致500错误的原因。我使用Django压缩器实用程序,我们的前端工程师在Django模板的压缩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 %}
The solution was to move the link to the ttf
file below the endcompress
line.
解决方案是将链接移动到endcompress line下面的ttf文件。
#24
-5
If you want to allow for all hosts. Use ALLOWED_HOSTS = ['*',] instead of ALLOWED_HOSTS = ['*']
如果您想允许所有的主机。使用ALLOWED_HOSTS =['*',]而不是ALLOWED_HOSTS = ['*']
#1
395
Django 1.5 introduced the allowed hosts setting that is required for security reasons. A settings file created with Django 1.5 has this new section which you need to add:
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 = []
Add your host here like ['www.beta800.net']
or ['*']
for a quick test, but don't use ['*']
for production.
在这里添加您的主机,如['www.beta800.net']或['*']进行快速测试,但不要将['*']用于生产。
#2
22
In my case, reading docs of third party apps properly saved me.
在我的案例中,阅读第三方应用程序的文档能够正确地拯救我。
The culprit? django_compressor
罪魁祸首吗?django_compressor
I had
我有
{% load compress %}
{% compress css %}
... css files linked here ..
{% endcompress %}
DEBUG = True
always gave me 500. To fix it, I needed a line in my settings to get it running
DEBUG = True总是给我500。为了修复它,我需要在我的设置中使用一行代码来运行它
COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False)
#3
21
I know this is late but I ended up here with a search for my error 500 with DEBUG=False
, in my case it did turn out to be the ALLOWED_HOSTS
but I was using os.environ.get('variable')
to populate the hosts, I did not notice this until I enabled logging, you can log all errors to file with the below and it will log even when DEBUG=False
:
我知道这是晚但我最终在这里寻找我的错误500 DEBUG = False,就我而言它确实是ALLOWED_HOSTS但我用os.environ.get(变量)来填充主机,我才注意到这个启用日志记录,可以用下面的所有错误日志文件并将日志即使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',
},
}
}
#4
12
Right, in Django 1.5 if DEBUG = False, configure ALLOWED_HOSTS, adding domains without the port number. example:
在Django 1.5中,如果DEBUG = False,配置ALLOWED_HOSTS,添加没有端口号的域。例子:
ALLOWED_HOSTS = ['localhost']
#5
9
You must also check your URLs all over the place. When the DEBUG
is set to False
, all URLs without trailing /
are treated as a bug, unlike when you have DEBUG = True
, in which case Django will append /
everywhere it is missing. So, in short, make sure all links end with a slash EVERYWHERE.
您还必须检查您的url各地。当调试被设置为False时,所有的url都被当作一个bug,不像你有DEBUG = True,在这种情况下,Django将附加/到处都没有。因此,简而言之,确保所有链接都以斜线结尾。
#6
6
I have a hilarious story for all. After reaching this page I said "Eureka! I'm saved. That MUST be my problem." So I inserted the required ALLOWED_HOSTS
list in setting.py and... nothing. Same old 500 error. And no, it wasn't for lack of a 404.html file.
我有一个有趣的故事。到了这一页后,我说:“找到了!”我得救了。那一定是我的问题。因此我在设置中插入了所需的ALLOWED_HOSTS列表。py和…什么都没有。老500错误。不,不是因为缺少404页面。html文件。
So for 2 days I busied myself with wild theories, such as that it had something to do with serving static files (understand that I am a noob and noobs don't know what they're doing).
因此,我花了两天时间研究一些疯狂的理论,比如它与提供静态文件有关(要知道我是noob, noobs不知道他们在做什么)。
So what was it? It is now Mr. Moderator that we come to a useful tip. Whereas my development Django is version 1.5.something, my production server version is 1.5.something+1... or maybe plus 2. Whatever. And so after I added the ALLOWED_HOSTS
to the desktop version of settings.py, which lacked what hwjp requested--- a "default value in settings.py, perhaps with an explanatory comment"--- I did the same on the production server with the proper domain for it.
那么是什么呢?现在是主持人先生,我们得到了一个有用的建议。而我的开发Django是1.5版。我的产品服务器版本是1.5.something+1…或者+ 2。无论什么。在我将ALLOWED_HOSTS添加到设置的桌面版本之后。py缺少hwjp所要求的——“设置中的默认值”。py,也许有一个解释性的注释“---我在生产服务器上做了相同的事情。
But I failed to notice that on the production server with the later version of Django there WAS a default value in settings.py with an explanatory comment. It was well below where I made my entry, out of sight on the monitor. And of course the list was empty. Hence my waste of time.
但是我没有注意到,在Django的后期版本的生产服务器上,设置中有一个默认值。带着解释性的评论。它就在我进去的地方下面,在监视器上看不见。当然名单是空的。因此我浪费时间。
#7
5
I faced the same problem when I did DEBUG = FALSE
. Here is a consolidated solution as scattered in answers above and other posts.
我在做DEBUG = FALSE时遇到了同样的问题。这里有一个综合的解决方案,分散在上面的答案和其他文章中。
By default, in settings.py we have ALLOWED_HOSTS = []
. Here are possible changes you will have to make in ALLOWED_HOSTS
value as per scenario to get rid of the error:
默认情况下,在设置。我们有ALLOWED_HOSTS =[]。为了消除错误,您可能需要根据场景在ALLOWED_HOSTS值中进行更改:
1: Your domain name:
1:你的域名:
ALLOWED_HOSTS = ['www.example.com'] # Your domain name here
2: Your deployed server IP if you don't have domain name yet (which was my case and worked like a charm):
2:如果你还没有域名,你部署的服务器IP(这是我的情况,而且工作起来很有魅力):
ALLOWED_HOSTS = ['123.123.198.123'] # Enter your IP here
3: If you are testing on local server, you can edit your settings.py
or settings_local.py
as:
3:如果您正在本地服务器上测试,您可以编辑您的设置。py或settings_local。py:
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
4: You can also provide '*' in the ALLOWED_HOSTS
value but its not recommended in the production environment due to security reasons:
4:您还可以在ALLOWED_HOSTS值中提供“*”,但出于安全原因,不建议在生产环境中提供:
ALLOWED_HOSTS = ['*'] # Not recommended in production environment
I have also posted a detailed solution on my blog which you may want to refer.
我还在我的博客上发布了一个详细的解决方案,你可以参考一下。
#8
5
For what it's worth - I was getting a 500 with DEBUG = False
on some pages only. Tracing back the exception with pdb revealed a missing asset (I suspect the {% static ... %}
template tag was the culprit for the 500.
值得注意的是,我只在某些页面上得到了500个DEBUG = False。用pdb跟踪异常发现了一个丢失的资产(我怀疑是{% static…%} template标签是500的罪魁祸首。
#9
5
I encountered the same issue just recently in Django 2.0. I was able to figure out the problem by setting DEBUG_PROPAGATE_EXCEPTIONS = True
. See here: https://docs.djangoproject.com/en/2.0/ref/settings/#debug-propagate-exceptions
我最近在Django 2.0中遇到了同样的问题。我可以通过设置debug_propagate_exception来解决这个问题= True。在这里看到的:https://docs.djangoproject.com/en/2.0/ref/settings/ # debug-propagate-exceptions
In my case, the error was ValueError: Missing staticfiles manifest entry for 'admin/css/base.css'
. I fixed that by locally running python manage.py collectstatic
.
在我的例子中,错误是ValueError:缺少“admin/css/base.css”的staticfiles清单条目。我通过本地运行python管理修复了这个问题。py collectstatic。
#10
5
Complementing the main answer
It is annoying to change the ALLOWED_HOSTS and DEBUG global constants in settings.py
when switching between development and production. I am using this code to set these setting automatically:
补充主要的答案,更改ALLOWED_HOSTS和调试设置中的全局常量非常烦人。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",]
...
If you use macOS you could write a more generic code:
如果您使用macOS,您可以编写更通用的代码:
if socket.gethostname().endswith(".local"): # True in your local computer
DEBUG = True
ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
else:
...
#11
4
ALLOWED_HOSTS is NOT the only issue, for me I had to make a 404.html and put it in the base level of my templates (not app level) - Also, you can make a 404 view and add a 404handler url but I think thats optional. 404.html fixed it
ALLOWED_HOSTS并不是唯一的问题,对我来说,我需要创建一个404。html并把它放在我的模板的基础层(不是应用程序层)——同样,你可以创建一个404视图并添加一个404handler url,但我认为这是可选的。404年。html固定它
in mainproject.urls
在mainproject.urls
handler404 = 'app.views.custom_404'
in app.views
在app.views
def custom_404(request):
return render(request, '404.html', {}, status=404)
then make a templates/404.html template
然后模板/ 404。html模板
got this from another S/O post that I cannot find it
从我找不到的另一个S/O帖子中得到这个。
EDIT
编辑
also, I get 500 errors when I serve assets with whitenoise. Could not figure that out for the life of me, error was ValueError from whitenoise not being able to find an asset that I also could not find, had to go with default django serving for now
另外,在使用whitenoise处理资产时,我将得到500个错误。我怎么也搞不清楚,错误是whitenoise的ValueError因为找不到我也找不到的资产,现在只能用django的默认值
#12
2
I know that this is a super old question, but maybe I could help some one else. If you are having a 500 error after setting DEBUG=False, you can always run the manage.py runserver in the command line to see any errors that wont appear in any web error logs.
我知道这是一个非常古老的问题,但也许我可以帮助别人。如果在设置DEBUG=False之后出现500个错误,则始终可以运行管理。在命令行中查看不会出现在任何web错误日志中的错误。
#13
2
I was searching and testing more about this issue and I realized that static files direcotiries specified in settings.py can be a cause of this, so fist, we need to run this command
我对这个问题进行了更多的搜索和测试,我意识到静态文件在设置中指定了direcotiries。py可能是原因之一,所以首先,我们需要运行这个命令
python manage.py collecstatic
in settings.py, the code should look something like this:
在设置。py,代码应该是这样的:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
#14
1
I think it could also be the http server settings. Mine is still broken and had ALLOWED_HOSTS the entire time. I can access it locally (i use gunicorn), but not via the domain name when DEBUG=False. when I try using the domain name it then gives me the error, so makes me think its a nginx related issue.
我认为它也可以是http服务器设置。我的仍然是坏的,并且一直允许主机运行。我可以在本地访问它(我使用gunicorn),但在DEBUG=False时不能通过域名访问它。当我尝试使用域名时,它会给我错误,所以我认为这是一个nginx相关的问题。
Here is my conf file for 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;
}
#15
1
I have the similar issue, in my case it was caused by having a Commented script inside the body tag.
我也遇到了类似的问题,在我的例子中,它是由body标记内的注释脚本引起的。
<!--<script> </script>-->
#16
1
I ran into this issue. Turns out I was including in the template, using the static
template tag, a file that did not exist anymore. A look in the logs showed me the problem.
我遇到了这个问题。原来我使用的是静态模板标签,一个不再存在的文件。看一下日志就知道问题出在哪儿了。
I guess this is just one of many possible reasons for this kind of error.
我想这只是造成这种错误的众多原因之一。
Moral of the story: always log errors and always check logs.
故事的寓意:总是记录错误,总是检查日志。
#17
1
Thanks to @squarebear, in the log file, I found the error: ValueError: The file 'myapp/styles.css' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage ...>
.
感谢@squarebear,在日志文件中,我发现了错误:ValueError:文件的myapp/样式。在< whitenoisee .storage中找不到css'。CompressedManifestStaticFilesStorage…>。
I had a few problems in my django app. I removed the lineSTATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
which I found from the heroku's documentation.
我的django应用程序有一些问题。我删除了STATICFILES_STORAGE = 'whitenoise.django。我从heroku的文档中找到的GzipManifestStaticFilesStorage。
I also had to add extra directory (thanks to another SO answer) static
in the root of django application as myapp/static
even though I wasn't using it. Then running the command python manage.py collectstatic
before running the server solved the problem. Finally, it started working fine.
我还必须在django应用程序的根中添加额外的目录(感谢另一个SO答案)静态作为myapp/static,尽管我没有使用它。然后运行命令python管理。在运行服务器之前,py collectstatic解决了这个问题。最后,它开始运行良好。
#18
0
I know this is an old question, but I was also getting a 500 error when DEBUG=False. After several hours, I realized I had forgot to end some of the links in my base.html with a trailing slash.
我知道这是个老问题,但是当DEBUG=False时,我也得到了500个错误。几个小时后,我意识到我忘记结束我基地的一些链接了。带有斜杠的html。
#19
0
This is old and my problem ended up being related to the problem but not for the OP but my solution is for anyone else who tried the above to no avail.
这是老问题,我的问题最终与问题有关,但不是针对OP,我的解决方案是针对任何尝试过上述方法的人。
I had a setting in a modified version of Django to minify CSS and JS files that only ran when DEBUG was off. My server did not have the CSS minifier installed and threw the error. If you are using Django-Mako-Plus, this might be your issue.
我在一个修改后的Django版本中设置了一个设置,用于缩小只有在调试关闭时才会运行的CSS和JS文件。如果您正在使用Django-Mako-Plus,这可能是您的问题。
#20
0
One small thing to note, If the array has None in it, then all the subsequent allowed hosts are ignored.
需要注意的一件小事是,如果数组中没有,则所有后续允许的主机将被忽略。
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
Django 1.8.4版本
#21
0
A bit late to the party, and off course there could be a legion of issues but I've had a similar issue and it turned out that I had {% %} special characters inside my html remark...
聚会有点晚了,当然会有很多问题,但我也遇到过类似的问题,结果发现我的html注释中有{%}特殊的字符……
<!-- <img src="{% static "my_app/myexample.jpg" %}" alt="My image"/> -->
#22
0
I had one view that threw a 500 error in debug=false but worked in debug=true. For anyone who is getting this kind of thing and Allowed Hosts is not the problem, I fixed my view by updating a template's static tag that was pointing to the wrong location.
我有一个视图在debug=false中抛出500个错误,但在debug=true中工作。对于任何得到这种东西并允许主机的人来说,都不是问题所在,我通过更新指向错误位置的模板的静态标记来修复我的视图。
So I'd suggest just checking links and tags are airtight in any templates used, maybe certain things slip through the net in debug but give errors in production.
因此,我建议在使用的任何模板中检查链接和标签都是密封的,也许在调试中某些东西会在网络中滑过,但是在生产中会出现错误。
#23
0
I found yet another cause of the 500 error when DEBUG=False. I use the Django compressor
utility and our front-end engineer added references to font files inside a compress css
block in a Django template. Like this:
在DEBUG=False时,我发现了另一个导致500错误的原因。我使用Django压缩器实用程序,我们的前端工程师在Django模板的压缩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 %}
The solution was to move the link to the ttf
file below the endcompress
line.
解决方案是将链接移动到endcompress line下面的ttf文件。
#24
-5
If you want to allow for all hosts. Use ALLOWED_HOSTS = ['*',] instead of ALLOWED_HOSTS = ['*']
如果您想允许所有的主机。使用ALLOWED_HOSTS =['*',]而不是ALLOWED_HOSTS = ['*']