为什么DEBUG=False设置会导致我的django静态文件访问失败?

时间:2023-01-17 13:39:25

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.

我正在用Django开发一个应用程序。到目前为止,一切都很好——指定了db设置、配置了静态目录、url、视图等等。但是,当我想要呈现我自己漂亮的自定义404时,麻烦就开始出现了。html和500。html页面。

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).

我阅读了关于自定义错误处理的文档,并在UrlsConf中设置了必要的配置,创建了相应的视图并添加了404。html和500年。html到我的应用的模板目录(在设置中指定)。py)。

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!

我不仅没有查看自定义404页面。html(实际上,它装载了错误页面,但是因为我的错误页面都包含了一个图形错误消息——就像一些漂亮的图片一样),错误页面的源装载了错误页面,但是没有其他东西装载!甚至连CSS或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?

通常,一旦我设置DEBUG = False,所有视图都会被加载,但是任何链接内容(CSS、Javascript、图像等)都不会被加载!发生什么事情了?关于静态文件和调试设置,是否缺少什么?

11 个解决方案

#1


245  

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.

调试关闭后,Django将不再为您处理静态文件——您的产品web服务器(Apache或其他)应该对此负责。

#2


367  

If you still need to server static locally (e.g. for testing without debug) you can run devserver in insecure mode:

如果您仍然需要在本地服务器静态(例如,在没有调试的情况下进行测试),您可以在不安全的模式下运行devserver:

manage.py runserver --insecure

#3


19  

You can use WhiteNoise to serve static files in production.

您可以使用WhiteNoise来处理生产中的静态文件。

Install:

安装:

pip install WhiteNoise

And change your wsgi.py file to this:

和改变你的wsgi。py文件:

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise

application = get_wsgi_application()
application = DjangoWhiteNoise(application)

And you're good to go!

你可以走了!

Credit to Handlebar Creative Blog.

归功于Handlebar创意博客。

BUT, it's really not recommended serving static files this way in production. Your production web server(like nginx) should take care of that.

但是,在生产中不建议以这种方式提供静态文件。您的产品web服务器(如nginx)应该对此负责。

#4


14  

If you are using the static serve view in development, you have to have DEBUG = True :

如果在开发中使用静态服务视图,则必须让DEBUG = True:

Warning

警告

This will only work if DEBUG is True.

这只有在调试是正确的情况下才有效。

That's because this view is grossly inefficient and probably insecure. This is only intended for local development, and should never be used in production.

这是因为这种观点非常低效,而且可能不安全。这只用于本地开发,不应在生产中使用。

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.

编辑:您可以添加一些url来测试404和500模板,只需在url中使用通用视图direct_to_template。

from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
    ('^404testing/$', direct_to_template, {'template': '404.html'})
)

#5


10  

You actually can serve static files in a production Django app, securely and without DEBUG=True.

实际上,您可以在一个产品Django应用程序中安全地服务静态文件,而不需要调试=True。

Rather than using Django itself, use dj_static in your WSGI file (github):

而不是使用Django本身,在您的WSGI文件(github)中使用dj_static:

# requirements.txt:

...
dj-static==0.0.6


# YOURAPP/settings.py:

...
STATIC_ROOT = 'staticdir'
STATIC_URL = '/staticpath/'

# YOURAPP/wsgi.py:

...
from django.core.wsgi import get_wsgi_application
from dj_static import Cling

application = Cling(get_wsgi_application())

#6


5  

Just open your project urls.py, then find this if statement.

打开你的项目url。py,然后找到这个if语句。

if settings.DEBUG:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )

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.

你可以改变设置。对True进行调试,它将始终工作。但是如果你的项目很重要,那么你应该考虑上面提到的其他解决方案。

if True:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )

In django 1.10 you can write so:

在django 1.10中,可以这样写:

urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), url(r'^static/(?P<path>.*)$', serve, { 'document_root': settings.STATIC_ROOT }), ]

#7


4  

You can debug this in many different ways. Here's my approach.

您可以用许多不同的方式调试它。这是我的方法。

localsettings.py:

localsettings.py:

DEBUG = False
DEBUG404 = True

urls.py:

urls . py:

from django.conf import settings
import os

if settings.DEBUG404:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', 'django.views.static.serve',
         {'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
    )

Be sure to read the docs ;)

一定要阅读文档;)

https://docs.djangoproject.com/en/2.0/howto/static-files/#limiting-use-to-debug-true

https://docs.djangoproject.com/en/2.0/howto/static-files/ limiting-use-to-debug-true

#8


4  

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:

强尼的回答很好,但是仅仅通过添加那些描述的台词对我来说还是不行。基于这个答案,我的实际工作步骤如下:

  1. Install WhiteNoise as described:

    安装WhiteNoise描述:

    pip install WhiteNoise
    
  2. Create the STATIC_ROOT variable and add WhiteNoise to your MIDDLEWARE variable in settings.py:

    创建STATIC_ROOT变量,并在settings.y中向中间件变量添加WhiteNoise。

    #settings.py
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'whitenoise.middleware.WhiteNoiseMiddleware', #add whitenoise
        'django.contrib.sessions.middleware.SessionMiddleware',
        ...
    ]
    
    #...
    
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ##specify static root
    
  3. Then, modify your wsgi.py file as explained in Johnny's answer:

    然后,修改您的wsgi。py文件在Johnny的回答中解释道:

    #wsgi.py
    from django.core.wsgi import get_wsgi_application
    from whitenoise.django import DjangoWhiteNoise
    
    application = get_wsgi_application()
    application = DjangoWhiteNoise(application)
    
  4. After that, deploy your changes to your server (with git or whatever you use).

    然后,将您的更改部署到服务器(使用git或任何您使用的内容)。

  5. Finally, run the collectstatic option from your manage.py on your server. This will copy all files from your static folders into the STATIC_ROOT directory we specified before:

    最后,从管理中运行collectstatic选项。py服务器上。这将从静态文件夹中复制所有文件到我们之前指定的STATIC_ROOT目录中:

    $ python manage.py collectstatic
    

    You will now see a new folder named staticfiles that contains such elements.

    现在您将看到一个名为staticfiles的新文件夹,其中包含此类元素。

After following these steps you can now run your server and will be able to see your static files while in Production mode.

在遵循这些步骤之后,您现在可以运行您的服务器,并且能够在生产模式下看到您的静态文件。

#9


1  

In urls.py I added this line:

在url。我加了一行:

from django.views.static import serve 

add those two urls in urlpatterns:

在urlpatterns中添加这两个url:

url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}), 
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), 

and both static and media files were accesible when DEBUG=FALSE.
Hope it helps :)

当DEBUG=FALSE时,可以同时使用静态文件和媒体文件。希望它能帮助:)

#10


0  

Support for string view arguments to url() is deprecated and will be removed in Django 1.10

对于url()的字符串视图参数的支持是不赞成的,将在Django 1.10中被删除。

My solution is just small correction to Conrado solution above.

我的解决方案是对上面的Conrado解决方案进行小的修正。

from django.conf import settings
import os
from django.views.static import serve as staticserve

if settings.DEBUG404:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', staticserve,
            {'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
        )

#11


0  

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

虽然它不是最安全的,但是您可以更改源代码。导航到Python / 2.7 /网站/ django url / conf / / static.py

Then edit like following:

然后编辑:

if settings.DEBUG or (prefix and '://' in prefix):

So then if settings.debug==False it won't effect on the code, also after running try python manage.py runserver --runserver to run static files.

因此,如果settings.debug==False,也不会对代码产生影响,同样在运行try python管理之后。py runserver——运行静态文件的runserver。

NOTE: Information should only be used for testing only

注意:信息只能用于测试

#1


245  

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.

调试关闭后,Django将不再为您处理静态文件——您的产品web服务器(Apache或其他)应该对此负责。

#2


367  

If you still need to server static locally (e.g. for testing without debug) you can run devserver in insecure mode:

如果您仍然需要在本地服务器静态(例如,在没有调试的情况下进行测试),您可以在不安全的模式下运行devserver:

manage.py runserver --insecure

#3


19  

You can use WhiteNoise to serve static files in production.

您可以使用WhiteNoise来处理生产中的静态文件。

Install:

安装:

pip install WhiteNoise

And change your wsgi.py file to this:

和改变你的wsgi。py文件:

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise

application = get_wsgi_application()
application = DjangoWhiteNoise(application)

And you're good to go!

你可以走了!

Credit to Handlebar Creative Blog.

归功于Handlebar创意博客。

BUT, it's really not recommended serving static files this way in production. Your production web server(like nginx) should take care of that.

但是,在生产中不建议以这种方式提供静态文件。您的产品web服务器(如nginx)应该对此负责。

#4


14  

If you are using the static serve view in development, you have to have DEBUG = True :

如果在开发中使用静态服务视图,则必须让DEBUG = True:

Warning

警告

This will only work if DEBUG is True.

这只有在调试是正确的情况下才有效。

That's because this view is grossly inefficient and probably insecure. This is only intended for local development, and should never be used in production.

这是因为这种观点非常低效,而且可能不安全。这只用于本地开发,不应在生产中使用。

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.

编辑:您可以添加一些url来测试404和500模板,只需在url中使用通用视图direct_to_template。

from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
    ('^404testing/$', direct_to_template, {'template': '404.html'})
)

#5


10  

You actually can serve static files in a production Django app, securely and without DEBUG=True.

实际上,您可以在一个产品Django应用程序中安全地服务静态文件,而不需要调试=True。

Rather than using Django itself, use dj_static in your WSGI file (github):

而不是使用Django本身,在您的WSGI文件(github)中使用dj_static:

# requirements.txt:

...
dj-static==0.0.6


# YOURAPP/settings.py:

...
STATIC_ROOT = 'staticdir'
STATIC_URL = '/staticpath/'

# YOURAPP/wsgi.py:

...
from django.core.wsgi import get_wsgi_application
from dj_static import Cling

application = Cling(get_wsgi_application())

#6


5  

Just open your project urls.py, then find this if statement.

打开你的项目url。py,然后找到这个if语句。

if settings.DEBUG:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )

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.

你可以改变设置。对True进行调试,它将始终工作。但是如果你的项目很重要,那么你应该考虑上面提到的其他解决方案。

if True:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )

In django 1.10 you can write so:

在django 1.10中,可以这样写:

urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), url(r'^static/(?P<path>.*)$', serve, { 'document_root': settings.STATIC_ROOT }), ]

#7


4  

You can debug this in many different ways. Here's my approach.

您可以用许多不同的方式调试它。这是我的方法。

localsettings.py:

localsettings.py:

DEBUG = False
DEBUG404 = True

urls.py:

urls . py:

from django.conf import settings
import os

if settings.DEBUG404:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', 'django.views.static.serve',
         {'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
    )

Be sure to read the docs ;)

一定要阅读文档;)

https://docs.djangoproject.com/en/2.0/howto/static-files/#limiting-use-to-debug-true

https://docs.djangoproject.com/en/2.0/howto/static-files/ limiting-use-to-debug-true

#8


4  

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:

强尼的回答很好,但是仅仅通过添加那些描述的台词对我来说还是不行。基于这个答案,我的实际工作步骤如下:

  1. Install WhiteNoise as described:

    安装WhiteNoise描述:

    pip install WhiteNoise
    
  2. Create the STATIC_ROOT variable and add WhiteNoise to your MIDDLEWARE variable in settings.py:

    创建STATIC_ROOT变量,并在settings.y中向中间件变量添加WhiteNoise。

    #settings.py
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'whitenoise.middleware.WhiteNoiseMiddleware', #add whitenoise
        'django.contrib.sessions.middleware.SessionMiddleware',
        ...
    ]
    
    #...
    
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ##specify static root
    
  3. Then, modify your wsgi.py file as explained in Johnny's answer:

    然后,修改您的wsgi。py文件在Johnny的回答中解释道:

    #wsgi.py
    from django.core.wsgi import get_wsgi_application
    from whitenoise.django import DjangoWhiteNoise
    
    application = get_wsgi_application()
    application = DjangoWhiteNoise(application)
    
  4. After that, deploy your changes to your server (with git or whatever you use).

    然后,将您的更改部署到服务器(使用git或任何您使用的内容)。

  5. Finally, run the collectstatic option from your manage.py on your server. This will copy all files from your static folders into the STATIC_ROOT directory we specified before:

    最后,从管理中运行collectstatic选项。py服务器上。这将从静态文件夹中复制所有文件到我们之前指定的STATIC_ROOT目录中:

    $ python manage.py collectstatic
    

    You will now see a new folder named staticfiles that contains such elements.

    现在您将看到一个名为staticfiles的新文件夹,其中包含此类元素。

After following these steps you can now run your server and will be able to see your static files while in Production mode.

在遵循这些步骤之后,您现在可以运行您的服务器,并且能够在生产模式下看到您的静态文件。

#9


1  

In urls.py I added this line:

在url。我加了一行:

from django.views.static import serve 

add those two urls in urlpatterns:

在urlpatterns中添加这两个url:

url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}), 
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), 

and both static and media files were accesible when DEBUG=FALSE.
Hope it helps :)

当DEBUG=FALSE时,可以同时使用静态文件和媒体文件。希望它能帮助:)

#10


0  

Support for string view arguments to url() is deprecated and will be removed in Django 1.10

对于url()的字符串视图参数的支持是不赞成的,将在Django 1.10中被删除。

My solution is just small correction to Conrado solution above.

我的解决方案是对上面的Conrado解决方案进行小的修正。

from django.conf import settings
import os
from django.views.static import serve as staticserve

if settings.DEBUG404:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', staticserve,
            {'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
        )

#11


0  

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

虽然它不是最安全的,但是您可以更改源代码。导航到Python / 2.7 /网站/ django url / conf / / static.py

Then edit like following:

然后编辑:

if settings.DEBUG or (prefix and '://' in prefix):

So then if settings.debug==False it won't effect on the code, also after running try python manage.py runserver --runserver to run static files.

因此,如果settings.debug==False,也不会对代码产生影响,同样在运行try python管理之后。py runserver——运行静态文件的runserver。

NOTE: Information should only be used for testing only

注意:信息只能用于测试