为什么 DEBUG=False 设置会使我的 django 静态文件访问失败?
我正在使用 Django 作为我的主力构建一个应用程序。到目前为止,一切都很顺利 - 指定的数据库设置、配置的静态目录、url、视图等。但是当我想要渲染自己漂亮的自定义 404.html 和 500.html 页面时,麻烦就开始出现了。
我阅读了有关自定义错误处理的文档,并在 UrlsConf 中设置了必要的配置,创建了相应的视图并将 404.html 和 500.html 添加到我的应用程序的模板目录(也在 settings.py 中指定)。
但文档说“您实际上可以查看自定义错误视图,直到调试关闭”,所以我确实将其关闭以测试我的东西,而那就是东西变得疯狂的时候!
我不仅无法查看自定义 404.html(实际上,它会加载,而且因为我的错误页面每个都包含一个图形错误消息 - 作为一些漂亮的图像),错误页面的源会加载,但不会加载其他内容!甚至没有链接 CSS 或 Javascript!
一般来说,一旦我设置 DEBUG = False,所有视图都会加载,但任何链接的内容(CSS、Javascript、图像等)都不会加载!发生什么事了?关于静态文件和 DEBUG 设置,是否缺少某些内容?
Am building an app using Django as my workhorse. All has been well so far - specified db settings, configured static directories, urls, views etc. But trouble started sneaking in the moment I wanted to render my own beautiful and custom 404.html and 500.html pages.
I read the docs on custom error handling, and set necessary configurations in UrlsConf, created corresponding views and added the 404.html and the 500.html to my app's template directory (specified in the settings.py too).
But the docs say "you can actually view custom error views until Debug is Off", so I did turn it off to test my stuff, and that's when stuff goes berserk!
Not only do I fail to view the custom 404.html (actually, it loads, but because my error pages each contain a graphic error message -as some nice image), the source of the error page loads, but nothing else loads! Not even linked CSS or Javascript!
Generally, once I set DEBUG = False
, all views will load, but any linked content (CSS, Javascript, Images, etc) wont load! What's happening? Is there something am missing, concerning static files and the DEBUG
setting?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(21)
如果您仍然需要在本地提供静态服务(例如,为了不进行调试而进行测试),您可以在不安全模式下运行 devserver:
If you still need to server static locally (e.g. for testing without debug) you can run devserver in insecure mode:
关闭调试后,Django 将不再为您处理静态文件 - 您的生产 Web 服务器(Apache 或其他)应该处理这个问题。
With debug turned off Django won't handle static files for you any more - your production web server (Apache or something) should take care of that.
首先,您需要在 settings.py 中添加 STATIC_ROOT。
确保 BASE_DIR 已定义。
然后,您需要在应用程序的根 urls.py 中添加以下代码。
然后您需要运行:
Lastly run:
现在您应该能够加载静态文件。
First you need to add STATIC_ROOT in your settings.py.
Make sure BASE_DIR is already defined.
Then you'll need to add following code in you app's root urls.py.
Then you'll need to run:
Lastly run:
and now you should be able to load your static files.
您可以使用 WhiteNoise 在生产中提供静态文件。
安装:
并将您的 wsgi.py 文件更改为:
这样就可以开始了!
感谢 Handlebar 创意博客。
但是,确实不建议在生产中以这种方式提供静态文件。你的生产网络服务器(比如 nginx)应该处理这个问题。
You can use WhiteNoise to serve static files in production.
Install:
And change your wsgi.py file to this:
And you're good to go!
Credit to Handlebar Creative Blog.
BUT, it's really not recommended serving static files this way in production. Your production web server(like nginx) should take care of that.
约翰尼的答案很棒,但仅通过添加那里描述的那些行仍然对我不起作用。根据该答案,实际对我有用的步骤如下:
安装 WhiteNoise 作为描述:
创建
STATIC_ROOT
变量并将 WhiteNoise 添加到settings.py
中的MIDDLEWARE
变量:然后,按照约翰尼的回答中的说明修改您的
wsgi.py
文件:之后,将您的更改部署到您的服务器(使用 git 或您使用的任何工具)。
最后,运行
collectstatic
< /a> 来自服务器上manage.py
的选项。这会将静态文件夹中的所有文件复制到我们之前指定的STATIC_ROOT
目录中:您现在将看到一个名为
staticfiles
的新文件夹,其中包含此类元素。执行这些步骤后,您现在可以运行服务器,并且能够在生产模式下查看静态文件。
更新:如果您的版本 4 changelog 表示不再需要声明 < code>WSGI_APPLICATION = 'projectName.wsgi.application' 在您的
settings.py
文件中。Johnny's answer is great, but still didn't work for me just by adding those lines described there. Based on that answer, the steps that actually worked for me where:
Install WhiteNoise as described:
Create the
STATIC_ROOT
variable and add WhiteNoise to yourMIDDLEWARE
variable insettings.py
:Then, modify your
wsgi.py
file as explained in Johnny's answer:After that, deploy your changes to your server (with git or whatever you use).
Finally, run the
collectstatic
option from yourmanage.py
on your server. This will copy all files from your static folders into theSTATIC_ROOT
directory we specified before:You will now see a new folder named
staticfiles
that contains such elements.After following these steps you can now run your server and will be able to see your static files while in Production mode.
Update: In case you had version < 4 the changelog indicates that it's no longer necessary to declare the
WSGI_APPLICATION = 'projectName.wsgi.application'
on yoursettings.py
file.如果您在开发中使用静态服务视图,则必须具有 DEBUG = True :
文档:在开发中提供静态文件
编辑:您可以添加一些网址来测试您的 404 和 500 模板,只需在您的网址中使用通用视图 direct_to_template 即可。
If you are using the static serve view in development, you have to have DEBUG = True :
Docs: serving static files in developent
EDIT: You could add some urls just to test your 404 and 500 templates, just use the generic view direct_to_template in your urls.
实际上,您可以在生产 Django 应用程序中安全地提供静态文件,并且无需
DEBUG=True
。不要使用 Django 本身,而是在 WSGI 文件中使用 dj_static (github):
requirements.txt:
YOURAPP/settings.py:
YOURAPP/wsgi.py:
You actually can serve static files in a production Django app, securely and without
DEBUG=True
.Rather than using Django itself, use dj_static in your WSGI file (github):
requirements.txt:
YOURAPP/settings.py:
YOURAPP/wsgi.py:
从这里我通过混合一些答案来寻求帮助。在这里,我添加了我的全部部分。 [我这样做是为了初学者的帮助以及我将来的使用]
首先,问题是为什么需要
Debug=False
!我把我的项目放在AWS中,几个小时后由于内存泄漏,连接超时。
一开始我想到了芹菜。 【当然我只是个初学者】
然后我将
DEBUG=True
中的DEBUG=False
正如我们可以在 settings.py 中看到的安全警告一旦我这样做,我的静态文件就没有在网页中成功加载。
然后我到处搜索,首先尝试从这里使用 --insecure 命令来运行服务器。
这是成功的,但我不希望我的项目在生产时使用不安全模式。
作为正确的解决方案[根据我],我按照以下步骤操作。
首先,我更正 settings.py 中的静态 URL、root 和 dir
然后通过命令收集静态文件
现在是第二步,[此处也提供了]
首先在命令行中的项目目录中安装whitenoise
,然后在settings.py中的中间件列表中添加“whitenoise.middleware.WhiteNoiseMiddleware”。
应该将其添加到“django.middleware.security.SecurityMiddleware”下方以及所有其余中间件上方。这样您的中间件列表将如下所示:-
在已安装的应用程序顶部添加“whitenoise.runserver_nostatic” 这样您已安装的应用程序列表将如下所示:-
完成,您现在将能够在生产中提供静态文件! [我也在我的本地环境中做了]
只需使用 runserver 命令,一如既往,没有不安全或任何需要的东西。
繁荣!!!它对我有用。
哈哈哈。我知道我的天性有点幼稚,但我现在很高兴。
感谢在这里提供答案并帮助我的工作的所有人。
From here I took help by mixing a few answers. Here, I am adding my whole parts. [I am doing this for a beginners help and for my future use as well]
Well at first the question is why
Debug=False
needed!I put my project in AWS and it was being connection timeout after few hours because of memory leaking.
At first I thought for celery. [of course I am just a beginner]
Then I put
DEBUG=False
fromDEBUG=True
As we can see the security warning in settings.pyOnce I did that my staticfiles were not loading successfully in webpages.
Then I searched everywhere and at first tried from here the --insecure command to runserver.
Which is successful but I don't want the insecure mode in my project when it is in production.
And as the proper solution [according to me] I followed the steps below.
At first, I correct the static URL,root, and dir in settings.py
Then collect the static files by command
Now the second step, [which also provided here]
At first install whitenoise in your project directory in the command line
Then Add 'whitenoise.middleware.WhiteNoiseMiddleware' in your middleware list in settings.py.
This should be added just below the 'django.middleware.security.SecurityMiddleware' and above all the remaining middleware. So that your middleware list will look like this:-
Add 'whitenoise.runserver_nostatic' on top of your installed apps So that your installed apps list will look like this:-
Done, you will be able to serve static files in production now!! [I did on my local environment as well]
Just use the runserver command as always no insecure or anything needed.
Boom!!! It's working for me.
Hahaha. I know kinda childish nature but I am so happy now.
Thanks to everyone who provided answers here and help my work.
最终解决方案:-
所以基本上当你设置 debug = False 时,Django 不想处理你的静态文件。
所以我们想要一些可以处理我们的文件的东西。
答案是白噪声。
在您的环境中安装白噪声
在 settings.py 的中间件列表中添加'whitenoise.middleware.WhiteNoiseMiddleware'。
应将其添加到'django.middleware.security.SecurityMiddleware'下方以及所有其余中间件上方。这样你的中间件列表将如下所示:-
<前><代码>中间件 = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# 准确地添加到这里
'django.contrib.sessions.middleware.SessionMiddleware',
'...'
]
在已安装的应用程序顶部添加'whitenoise.runserver_nostatic'
这样您安装的应用程序列表将如下所示:-
<前><代码>INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'django.contrib.admin',
'django.contrib.auth',
'...'
]
完成,您现在将能够在生产中提供静态文件!
Ultimate solution:-
So basically when you make debug = False, Django doesn't want to take care of your static files.
So we want something that can take care of our files.
The answer is whitenoise.
pip install whitenoise in your environment
Add 'whitenoise.middleware.WhiteNoiseMiddleware' in your middleware list in settings.py.
This should be added just below the 'django.middleware.security.SecurityMiddleware' and above all the remaining middleware. So that your middleware list will look like this:-
Add 'whitenoise.runserver_nostatic' on top of your installed apps
So that your installed apps list will look like this:-
Done, you will be able to serve static files in production now!!
您可以通过多种不同的方式对此进行调试。这是我的方法。
localsettings.py:
urls.py:
请务必阅读文档;)
https://docs.djangoproject.com/en/2.0/howto/static-files/#limiting-use-to-debug-true
You can debug this in many different ways. Here's my approach.
localsettings.py:
urls.py:
Be sure to read the docs ;)
https://docs.djangoproject.com/en/2.0/howto/static-files/#limiting-use-to-debug-true
这正是您必须在终端上键入才能运行项目而无需 DEBUG = TRUE
然后您会看到所有资产(静态)文件都在本地服务器上正确加载。
--insecure
:这意味着您可以在没有安全模式的情况下运行服务器This is Exactly you must type on terminal to run your project without DEBUG = TRUE
and then you see all assets (static) file is loading correctly On local server .
--insecure
: it means you can run server without security mode对于 Django 的最新版本,请查看此处的答案:https://stackoverflow.com/a/7639983/6180987
<对于低于 1.10 的 django 版本,解决方案应该有效:
只需打开项目 urls.py,然后找到此 if 语句。
您可以将 settings.DEBUG 更改为 True,它将始终有效。但如果您的项目是一个严肃的项目,那么您应该考虑上面提到的其他解决方案。
在 django 1.10 中你可以这样写:
For last versions of Django please look at the answer here: https://stackoverflow.com/a/7639983/6180987
For django version below 1.10 the solution should work:
Just open your project urls.py, then find this if statement.
You can change settings.DEBUG on True and it will work always. But if your project is a something serious then you should to think about other solutions mentioned above.
In django 1.10 you can write so:
我同意 Marek Sapkota 的回答;但如果请求静态文件,您仍然可以使用 django URFConf 重新分配 url。
第 1 步:在 settings.py 中定义
STATIC_ROOT
路径第 2 步:然后收集静态文件
第 3 步:现在定义您的 URLConf,如果 static 位于 url 的开头,则从静态文件夹访问文件 <代码>静态文件。注意:这是您项目的 urls.py 文件:
I agree with Marek Sapkota answer; But you can still use django URFConf to reallocate the url, if static file is requested.
Step 1: Define a
STATIC_ROOT
path in settings.pyStep 2: Then collect the static files
Step 3: Now define your URLConf that if static is in the beginning of url, access files from the static folder
staticfiles
. NOTE: This is your project's urls.py file:当我设置
DEBUG = True
时,我的静态代码不起作用。如果我在 python manage.py runserver --insecure 中运行我的项目。通过这个我也得到了我的静电。
解决方案 1:
解决方案 2:
但我需要永久解决方案。然后我安装
pip install dj-static==0.0.6
并向我的 wsgi.py 文件添加一些代码:然后我在setting.py中添加一些代码:
when i make
DEBUG = True
my static are doesn't work.if i run my project in
python manage.py runserver --insecure
. By this i got my static as well.Solution 1:
Solution 2:
But I Need Permanent Solution. then i install
pip install dj-static==0.0.6
and add some code to my wsgi.py file:and then i added some in setting.py:
我今天遇到了这个问题,并在开发过程中解决了这个问题,如果您仍然需要在本地提供静态服务(例如,用于不调试的测试),您可以在不安全模式下运行 devserver:
manage.py runserver --insecure
不用担心,因为在生产中,这个托管平台(Apache、Heroku ETC)将为您处理静态文件服务。
注意:Heroku 不提供静态文件,您希望将其放在 AWS 或 MS Azure 上
I got this problem today and this fixed it while on development, If you still need to server static locally (e.g. for testing without debug) you can run devserver in insecure mode:
manage.py runserver --insecure
Don't worry because when in production, this hosting platform (Apache, Heroku E.T.C ) would handle serving the static files for you.
Note: Heroku Doesn't server static files, you'd want to put it on AWS or MS Azure
nginx、设置和 url 配置
如果您使用的是 Linux,这可能会有所帮助。
nginx file
your_machn:/#vim etc/nginx/sites-available/nginxfile
urls.py
settings.py
确保运行:
nginx,settings and url configs
If you're on linux this may help.
nginx file
your_machn:/#vim etc/nginx/sites-available/nginxfile
urls.py
settings.py
Ensure to run:
这是正常且有意的行为。
如果 Django 只是从文件系统读取并发送文件,那么它比普通的 Web 服务器没有优势,所有 Web 服务器都能够自行提供文件服务。
此外,如果使用 Django 提供静态文件,Python 进程将在请求期间保持忙碌,并且无法提供更适合的动态请求。
由于这些原因,Django 静态视图仅设计用于开发期间使用,如果您的 DEBUG 设置为 False,则该视图将不起作用。
由于在开发过程中,我们通常一次只有一个人访问该站点(
开发人员),Django 可以很好地提供静态文件。
This is normal and intended behavior.
If Django is just reading from the filesystem and sending out a file, then it has no advantage over a normal web server, all web servers are capable to server the files on it's own.
Furthermore, if you serve static files with Django, you will keep the Python process busy for the duration of the request and it will be unable to serve the dynamic requests to which it is more suited.
For these reasons, the Django static view is designed only for use during development and will not work if your DEBUG setting is False.
Since during development we only usually have one person accessing the site at a time (the
developer), Django is fine to serve static files.
在生产模式下,静态文件不再由 Django 提供服务,而是应由 Apache 或 NGINX 提供服务,因此您需要配置它们。
另一方面,如果您想让 Django 为它们提供服务,那么下面的代码有助于在
DEBUG=False
时让 Django 提供静态文件。您可以通过将以下代码附加到主
urls.py
文件来尝试:然后,执行“collectstatic”:
归功于 @stathoula。按照她的回答以及 @leopd 的评论(在她的回答中添加
re_path
)。In production mode, the static files are no longer served by Django, but rather they should be served by Apache or NGINX, and hence you will need to configure them.
On the other hand, in case you wanted to let Django serve them, then the code below helps to let the static files be served by Django when
DEBUG=False
.You can try it by appending the code below to the main
urls.py
file:Then, do "collectstatic":
Credit to @stathoula. Following her answer along with the remark of @leopd (adding
re_path
to her answer).对 url() 的字符串视图参数的支持已被弃用,并将在 Django 1.10 中删除
我的解决方案只是对上面 Conrado 解决方案的小修正。
Support for string view arguments to url() is deprecated and will be removed in Django 1.10
My solution is just small correction to Conrado solution above.
我对我的 project/urls.py 进行了以下更改,它对我有用
添加此行:
从 django.conf.urls 导入 url
并添加:
url(r'^media/(?P.*)$',serve, {'document_root':settings.MEDIA_ROOT, })
,在 url 模式中。
I did the following changes to my project/urls.py and it worked for me
Add this line :
from django.conf.urls import url
and add :
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, })
,in urlpatterns.
虽然这不是最安全的,但是你可以在源代码中进行更改。导航到 Python/2.7/site-packages/django/conf/urls/static.py
然后进行如下编辑:
那么如果
settings.debug==False
它将不会'对代码没有影响,运行后也尝试使用python manage.py runserver --runserver
来运行静态文件。注意:信息只能用于测试
Although it's not safest, but you can change in the source code. navigate to
Python/2.7/site-packages/django/conf/urls/static.py
Then edit like following:
So then if
settings.debug==False
it won't effect on the code, also after running trypython manage.py runserver --runserver
to run static files.NOTE: Information should only be used for testing only