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

发布于 2024-11-04 00:55:40 字数 533 浏览 9 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

乱了心跳 2024-11-11 00:55:40

如果您仍然需要在本地提供静态服务(例如,为了不进行调试而进行测试),您可以在不安全模式下运行 devserver:

manage.py runserver --insecure

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
笨死的猪 2024-11-11 00:55:40

关闭调试后,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.

沉默的熊 2024-11-11 00:55:40

首先,您需要在 settings.py 中添加 STATIC_ROOT。

STATIC_ROOT = BASE_DIR / 'static'

确保 BASE_DIR 已定义。

然后,您需要在应用程序的根 urls.py 中添加以下代码。

from django.urls import re_path
from django.views.static import serve
from django.conf import settings


urlpatterns = [
    # your other paths here
    re_path(r'^media/(?P<path>.*)

然后您需要运行:

python manage.py collectstatic

Lastly run:

python manage.py runserver

现在您应该能够加载静态文件。

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

然后您需要运行:


Lastly run:


现在您应该能够加载静态文件。

, serve,{'document_root': settings.STATIC_ROOT}), ]

然后您需要运行:

Lastly run:

现在您应该能够加载静态文件。

First you need to add STATIC_ROOT in your settings.py.

STATIC_ROOT = BASE_DIR / 'static'

Make sure BASE_DIR is already defined.

Then you'll need to add following code in you app's root urls.py.

from django.urls import re_path
from django.views.static import serve
from django.conf import settings


urlpatterns = [
    # your other paths here
    re_path(r'^media/(?P<path>.*)

Then you'll need to run:

python manage.py collectstatic

Lastly run:

python manage.py runserver

and now you should be able to load your static files.

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

Then you'll need to run:


Lastly run:


and now you should be able to load your static files.

, serve,{'document_root': settings.STATIC_ROOT}), ]

Then you'll need to run:

Lastly run:

and now you should be able to load your static files.

-柠檬树下少年和吉他 2024-11-11 00:55:40

您可以使用 WhiteNoise 在生产中提供静态文件。

安装:

pip install WhiteNoise==2.0.6

并将您的 wsgi.py 文件更改为:

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

application = get_wsgi_application()
application = DjangoWhiteNoise(application)

这样就可以开始了!

感谢 Handlebar 创意博客

但是,确实不建议在生产中以这种方式提供静态文件。你的生产网络服务器(比如 nginx)应该处理这个问题。

You can use WhiteNoise to serve static files in production.

Install:

pip install WhiteNoise==2.0.6

And change your wsgi.py file to this:

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.

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

东风软 2024-11-11 00:55:40

约翰尼的答案很棒,但仅通过添加那里描述的那些行仍然对我不起作用。根据该答案,实际对我有用的步骤如下:

  1. 安装 WhiteNoise 作为描述:

    pip 安装 WhiteNoise
    
  2. 创建STATIC_ROOT 变量并将 WhiteNoise 添加到 settings.py 中的 MIDDLEWARE 变量:

    #settings.py
    中间件 = [
        'django.middleware.security.SecurityMiddleware',
        'whitenoise.middleware.WhiteNoiseMiddleware', #add Whitenoise
        'django.contrib.sessions.middleware.SessionMiddleware',
        ...
    ]
    
    #...
    
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ##指定静态根
    
  3. 然后,按照约翰尼的回答中的说明修改您的 wsgi.py 文件:

    #wsgi.py
    从 django.core.wsgi 导入 get_wsgi_application
    从whitenoise.django导入DjangoWhiteNoise
    
    应用程序 = get_wsgi_application()
    应用程序 = DjangoWhiteNoise(应用程序)
    
  4. 之后,将您的更改部署到您的服务器(使用 git 或您使用的任何工具)。

  5. 最后,运行collectstatic< /a> 来自服务器上 manage.py 的选项。这会将静态文件夹中的所有文件复制到我们之前指定的 STATIC_ROOT 目录中:

    $ python manage.pycollectstatic
    

    您现在将看到一个名为 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:

  1. Install WhiteNoise as described:

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

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

  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:

    $ python manage.py collectstatic
    

    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 your settings.py file.

毅然前行 2024-11-11 00:55:40

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

警告

只有当 DEBUG 为 True 时,这才有效。

那是因为这个观点很严重
效率低下并且可能不安全。
这仅适用于本地
开发,并且永远不应该使用
正在生产中。

文档:在开发中提供静态文件

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

from django.views.generic.simple import direct_to_template

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

If you are using the static serve view in development, you have to have 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.

from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
    ('^404testing/
, direct_to_template, {'template': '404.html'})
)
南街女流氓 2024-11-11 00:55:40

实际上,您可以在生产 Django 应用程序中安全地提供静态文件,并且无需 DEBUG=True

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

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

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:

...
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())
清旖 2024-11-11 00:55:40

从这里我通过混合一些答案来寻求帮助。在这里,我添加了我的全部部分。 [我这样做是为了初学者的帮助以及我将来的使用]

首先,问题是为什么需要Debug=False
我把我的项目放在AWS中,几个小时后由于内存泄漏,连接超时。
一开始我想到了芹菜。 【当然我只是个初学者】
然后我将 DEBUG=True 中的 DEBUG=False 正如我们可以在 settings.py 中看到的安全警告

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

一旦我这样做,我的静态文件就没有在网页中成功加载。
然后我到处搜索,首先尝试从这里使用 --insecure 命令来运行服务器。

python manage.py runserver --insecure

这是成功的,但我不希望我的项目在生产时使用不安全模式。
作为正确的解决方案[根据我],我按照以下步骤操作。

首先,我更正 settings.py 中的静态 URL、root 和 dir

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

然后通过命令收集静态文件

python manage.py collectstatic

现在是第二步,[此处也提供了]
首先在命令行中的项目目录中安装whitenoise

pip install whitenoise

,然后在settings.py中的中间件列表中添加“whitenoise.middleware.WhiteNoiseMiddleware”。

应该将其添加到“django.middleware.security.SecurityMiddleware”下方以及所有其余中间件上方。这样您的中间件列表将如下所示:-

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware', #after this line
    'whitenoise.middleware.WhiteNoiseMiddleware', #add it exactlyhere
    'django.contrib.sessions.middleware.SessionMiddleware', #before this
    '...'
]

在已安装的应用程序顶部添加“whitenoise.runserver_nostatic” 这样您已安装的应用程序列表将如下所示:-

INSTALLED_APPS = [
    'whitenoise.runserver_nostatic',
    'django.contrib.admin',
    'django.contrib.auth',
    '...'
]

完成,您现在将能够在生产中提供静态文件! [我也在我的本地环境中做了]

只需使用 runserver 命令,一如既往,没有不安全或任何需要的东西。

python manage.py 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 from DEBUG=True As we can see the security warning in settings.py

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

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

python manage.py runserver --insecure

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

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Then collect the static files by command

python manage.py collectstatic

Now the second step, [which also provided here]
At first install whitenoise in your project directory in the command line

pip install whitenoise

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:-

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware', #after this line
    'whitenoise.middleware.WhiteNoiseMiddleware', #add it exactlyhere
    'django.contrib.sessions.middleware.SessionMiddleware', #before this
    '...'
]

Add 'whitenoise.runserver_nostatic' on top of your installed apps So that your installed apps list will look like this:-

INSTALLED_APPS = [
    'whitenoise.runserver_nostatic',
    'django.contrib.admin',
    'django.contrib.auth',
    '...'
]

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.

python manage.py runserver

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.

盛夏尉蓝 2024-11-11 00:55:40

最终解决方案:-

所以基本上当你设置 debug = False 时,Django 不想处理你的静态文件。

所以我们想要一些可以处理我们的文件的东西。

答案是白噪声。

  1. 在您的环境中安装白噪声

  2. 在 settings.py 的中间件列表中添加'whitenoise.middleware.WhiteNoiseMiddleware'

    应将其添加到'django.middleware.security.SecurityMiddleware'下方以及所有其余中间件上方。这样你的中间件列表将如下所示:-

    <前><代码>中间件 = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    # 准确地添加到这里
    'django.contrib.sessions.middleware.SessionMiddleware',
    '...'
    ]

  3. 在已安装的应用程序顶部添加'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.

  1. pip install whitenoise in your environment

  2. 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:-

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'whitenoise.middleware.WhiteNoiseMiddleware',
        # add it exactlyhere
        'django.contrib.sessions.middleware.SessionMiddleware',
        '...'
    ]
    
  3. Add 'whitenoise.runserver_nostatic' on top of your installed apps
    So that your installed apps list will look like this:-

    INSTALLED_APPS = [
        'whitenoise.runserver_nostatic',
        'django.contrib.admin',
        'django.contrib.auth',
        '...'
    ]
    

Done, you will be able to serve static files in production now!!

郁金香雨 2024-11-11 00:55:40

您可以通过多种不同的方式对此进行调试。这是我的方法。

localsettings.py:

DEBUG = False
DEBUG404 = True

urls.py:

from django.conf import settings
import os

if settings.DEBUG404:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)

请务必阅读文档;)

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

, 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), 'static')} ), )

请务必阅读文档;)

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:

DEBUG = False
DEBUG404 = True

urls.py:

from django.conf import settings
import os

if settings.DEBUG404:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)

Be sure to read the docs ;)

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

, '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

烟花肆意 2024-11-11 00:55:40

这正是您必须在终端上键入才能运行项目而无需 DEBUG = TRUE
然后您会看到所有资产(静态)文件都在本地服务器上正确加载。

python manage.py runserver --insecure 

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

python manage.py runserver --insecure 

--insecure : it means you can run server without security mode

一直在等你来 2024-11-11 00:55:40

对于 Django 的最新版本,请查看此处的答案:https://stackoverflow.com/a/7639983/6180987

<对于低于 1.10 的 django 版本,解决方案应该有效:

只需打开项目 urls.py,然后找到此 if 语句。

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

您可以将 settings.DEBUG 更改为 True,它将始终有效。但如果您的项目是一个严肃的项目,那么您应该考虑上面提到的其他解决方案。

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

在 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 }), ]

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.

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.

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:

urlpatterns += [ url(r'^media/(?P<path>.*)
, serve, { 'document_root': settings.MEDIA_ROOT, }), url(r'^static/(?P<path>.*)
, serve, { 'document_root': settings.STATIC_ROOT }), ]
很酷不放纵 2024-11-11 00:55:40

我同意 Marek Sapkota 的回答;但如果请求静态文件,您仍然可以使用 django URFConf 重新分配 url。

第 1 步:在 settings.py 中定义 STATIC_ROOT 路径

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

第 2 步:然后收集静态文件

$ python manage.py collectstatic

第 3 步:现在定义您的 URLConf,如果 static 位于 url 的开头,则从静态文件夹访问文件 <代码>静态文件。注意:这是您项目的 urls.py 文件:

from django.urls import re_path
from django.views.static import serve

urlpattern += [
  re_path(r'^static/(?:.*)
, serve, {'document_root': settings.STATIC_ROOT, })
]

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

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Step 2: Then collect the static files

$ python manage.py collectstatic

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:

from django.urls import re_path
from django.views.static import serve

urlpattern += [
  re_path(r'^static/(?:.*)
, serve, {'document_root': settings.STATIC_ROOT, })
]
自由如风 2024-11-11 00:55:40

当我设置 DEBUG = True 时,我的静态代码不起作用。

如果我在 python manage.py runserver --insecure 中运行我的项目。通过这个我也得到了我的静电。

解决方案 1:

python manage.py runserver --insecure

解决方案 2:

但我需要永久解决方案。然后我安装 pip install dj-static==0.0.6 并向我的 wsgi.py 文件添加一些代码:

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

application = Cling(get_wsgi_application())

然后我在setting.py中添加一些代码:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
STATICFILES_DIRS = [
    BASE_DIR / "static",
]

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:

python manage.py runserver --insecure

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:

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

application = Cling(get_wsgi_application())

and then i added some in setting.py:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
STATICFILES_DIRS = [
    BASE_DIR / "static",
]
顾忌 2024-11-11 00:55:40

我今天遇到了这个问题,并在开发过程中解决了这个问题,如果您仍然需要在本地提供静态服务(例如,用于不调试的测试),您可以在不安全模式下运行 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

夏见 2024-11-11 00:55:40

nginx、设置和 url 配置

如果您使用的是 Linux,这可能会有所帮助。

nginx file

your_machn:/#vim etc/nginx/sites-available/nginxfile

server {
    server_name xyz.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /var/www/your_prj;
    }

    location /media/ {
        root /var/www/your_prj;
    }
...........
......
}

urls.py

.........
   .....
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('test/', test_viewset.TestServer_View.as_view()),
        path('api/private/', include(router_admin.urls)),
        path('api/public/', include(router_public.urls)),    
        ]
    
    if settings.DEBUG:
        import debug_toolbar
        urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

settings.py

.....
........
STATIC_URL = '/static/'
MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
.....
....

确保运行:

(venv)yourPrj$ ./manage.py collectstatic
yourSys# systemctrl daemon-reload

nginx,settings and url configs

If you're on linux this may help.

nginx file

your_machn:/#vim etc/nginx/sites-available/nginxfile

server {
    server_name xyz.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /var/www/your_prj;
    }

    location /media/ {
        root /var/www/your_prj;
    }
...........
......
}

urls.py

.........
   .....
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('test/', test_viewset.TestServer_View.as_view()),
        path('api/private/', include(router_admin.urls)),
        path('api/public/', include(router_public.urls)),    
        ]
    
    if settings.DEBUG:
        import debug_toolbar
        urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

settings.py

.....
........
STATIC_URL = '/static/'
MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
.....
....

Ensure to run:

(venv)yourPrj$ ./manage.py collectstatic
yourSys# systemctrl daemon-reload
放低过去 2024-11-11 00:55:40

这是正常且有意的行为。

Warning

This will only work if DEBUG is True.  
you can actually view custom error views until Debug is Off  

如果 Django 只是从文件系统读取并发送文件,那么它比普通的 Web 服务器没有优势,所有 Web 服务器都能够自行提供文件服务。

此外,如果使用 Django 提供静态文件,Python 进程将在请求期间保持忙碌,并且无法提供更适合的动态请求。

由于这些原因,Django 静态视图仅设计用于开发期间使用,如果您的 DEBUG 设置为 False,则该视图将不起作用。

由于在开发过程中,我们通常一次只有一个人访问该站点(
开发人员),Django 可以很好地提供静态文件。

This is normal and intended behavior.

Warning

This will only work if DEBUG is True.  
you can actually view custom error views until Debug is Off  

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.

亚希 2024-11-11 00:55:40

在生产模式下,静态文件不再由 Django 提供服务,而是应由 Apache 或 NGINX 提供服务,因此您需要配置它们。

另一方面,如果您想让 Django 为它们提供服务,那么下面的代码有助于在 DEBUG=False 时让 Django 提供静态文件。

您可以通过将以下代码附加到主 urls.py 文件来尝试:

from django.urls import re_path
from django.views.static import serve


urlpatterns += (
re_path(r'^media/(?P<path>.*)

然后,执行“collectstatic”:

python manage.py collectstatic

归功于 @stathoula。按照她的回答以及 @leopd 的评论(在她的回答中添加 re_path)。

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

然后,执行“collectstatic”:


归功于 @stathoula。按照她的回答以及 @leopd 的评论(在她的回答中添加 re_path)。

, serve,{'document_root': settings.STATIC_ROOT}), )

然后,执行“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:

from django.urls import re_path
from django.views.static import serve


urlpatterns += (
re_path(r'^media/(?P<path>.*)

Then, do "collectstatic":

python manage.py collectstatic

Credit to @stathoula. Following her answer along with the remark of @leopd (adding re_path to her answer).

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

Then, do "collectstatic":


Credit to @stathoula. Following her answer along with the remark of @leopd (adding re_path to her answer).

, serve,{'document_root': settings.STATIC_ROOT}), )

Then, do "collectstatic":

Credit to @stathoula. Following her answer along with the remark of @leopd (adding re_path to her answer).

凉薄对峙 2024-11-11 00:55:40

对 url() 的字符串视图参数的支持已被弃用,并将在 Django 1.10 中删除

我的解决方案只是对上面 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')} ),
        )

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.

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')} ),
        )
我的奇迹 2024-11-11 00:55:40

我对我的 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.

醉梦枕江山 2024-11-11 00:55:40

虽然这不是最安全的,但是你可以在源代码中进行更改。导航到 Python/2.7/site-packages/django/conf/urls/static.py

然后进行如下编辑:

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

那么如果 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:

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.

NOTE: Information should only be used for testing only

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文