禁用调试时静态文件不在 Django 2.2 中呈现

Static files not rendering in Django 2.2 when debug disabled

在 Django 2.2 中,当我有 DEBUG=True 时,我所有的静态文件都可以正常渲染。但是当我设置 DEBUG=False 来测试我的生产设置时,所有静态文件 URL 突然 return 404 错误。

我的项目结构如下:

myproject/
    myproject/
        settings.py
        urls.py
    manage.py
static/
    thumbnails/
         image.png

我在settings.py中的相关静态设置:

 STATIC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'static'))

 INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
ROOT_URLCONF = 'myproject.urls'
STATIC_URL = '/static/'
DEBUG = False

我的 urls.py 看起来像:

import os

from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

为什么像 http://localhost:8000/static/thumbnails/image.png 这样的 url 在调试打开时工作正常,但 return 在调试关闭时出现 404?

在生产中,您应该 运行 python manage.py collectstatic,并实际从某个地方提供您的静态文件。

If you look at the docs for static files,你会看到

Serving the files

In addition to these configuration steps, you’ll also need to actually serve the static files.

During development, if you use django.contrib.staticfiles, this will be done automatically by runserver when DEBUG is set to True (see django.contrib.staticfiles.views.serve()).

This method is grossly inefficient and probably insecure, so it is unsuitable for production.

See Deploying static files for proper strategies to serve static files in production environments.

您应该将生产设置中的 STATIC_ROOT 设置为网络服务器上的一个文件夹,并将您的网络服务器配置为将您的 STATIC_URL 指向该文件夹。参见 here.

在您的情况下,您似乎已经采取了所有这些步骤,除了实际提供您的静态文件。您可以通过将 Web 服务器指向正确的文件夹,或从 CDN 或其他解决方案为您提供静态文件来实现这一点。 Here's how to do it using apache

Django 从未打算取代网络服务器。来自 Django 文档:

Django doesn’t serve files itself; it leaves that job to whichever Web server you choose.

这种方法效率非常低,而且可能不安全,因此不适合生产。 在 localhostDEBUG = TRUE 上,它部署静态文件。在生产环境中,您应该使用 Web 服务器(Apache、'Nginx' etc)来部署静态文件。 只需在 Web 服务器的配置文件中列出静态目录即可。有关部署的更多详细说明,请参见 here