Django:Whitenoise 无法在生产环境中使用 debug false

Django: Whitenoise not working in production with debug false

我有一个 Django 应用程序,它带有用于静态文件的白噪声。但是当我使用 Google Lighthouse 测试应用程序时,我被要求为我的静态 .js 和 .css 文件启用文本压缩。

我阅读了很多相关帖子,但找不到答案。

我也按照 Heroku 的指南来实现它。 https://devcenter.heroku.com/articles/django-assets

设置

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django_user_agents.middleware.UserAgentMiddleware',
]

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

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

我也使用 Dropbox 存储媒体文件,但这似乎不是问题,我将其删除但仍然存在静态文件问题。

DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage'

要求

我确实在要求中包含了最新的 Whitenoise,并且在部署 Heroku 时没有出现错误:

whitenoise==4.1.2

在Lighthouse 中测试时,要求压缩此文件。它们来自 Static 文件夹,我知道当我 运行 Manage.py collectstatic

时它们应该被压缩
…css/bootstrap.min.css(afternoon-wildwood-39943.herokuapp.com)
…js/jquery-3.2.1.min.js(afternoon-wildwood-39943.herokuapp.com)
…js/bootstrap-table.min.js(afternoon-wildwood-39943.herokuapp.com)
…css/Fran%20Style.css(afternoon-wildwood-39943.herokuapp.com)
…js/popper.min.js(afternoon-wildwood-39943.herokuapp.com)

调试设置

我读到也许应该将 debug 设置为 False 才能使其正常工作。上面的例子是用 Debug = True 完成的。

DEBUG = bool(os.environ.get('DJANGO_DEBUG', True))

应用程序在这种情况下运行良好,但如果将调试设置为 False,我将收到错误 500 页面。

我在 Heroku 托管。您可以尝试以下示例:http://afternoon-wildwood-39943.herokuapp.com/website/

有线索吗?提前致谢!

感谢 Heroku 的支持,我找到了这个问题的解决方案。现在我的应用程序在 debug 设置为 false 的情况下工作正常,我得到了 whitenoise 提供的 Gzip 静态文件。

静态收集

首先,您应该 运行 在将应用程序部署到 Heroku 之前使用 collectstatic 命令,我一直认为这是在部署之后要做的事情。

Procfile

在 procfile 中,您应该添加以下代码行:

release: python manage.py migrate