所以这是Django用户的一个常见错误,即Debug=False
时生产中没有提供静态文件。我尝试了很多方法来克服这个问题,但仍然无法找到正确的解决方案。以下是我的设置.py
...
DEBUG = False
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]
...
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'main/static'),
os.path.join(BASE_DIR, 'member/static'),
os.path.join(BASE_DIR, 'register/static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
我看不出我怎么做错了。
*一个可能的原因是,从最初部署到heroku服务器以来,我已经设置了DISABLE_COLLECTSTATIC=1
。
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Building on the Heroku-20 stack
remote: -----> Using buildpack: heroku/python
remote: -----> Python app detected
remote: -----> Using Python version specified in runtime.txt
remote: -----> No change in requirements detected, installing from cache
remote: -----> Using cached install of python-3.7.12
remote: -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0
remote: -----> Installing SQLite3
remote: -----> Installing requirements with pip
remote: -----> Skipping Django collectstatic since the env var DISABLE_COLLECTSTATIC is set.
remote: -----> Discovering process types
remote: Procfile declares types -> web
remote:
remote: -----> Compressing...
remote: Done: 102.1M
remote: -----> Launching...
remote: Released v153
试试这个:
- 将已安装的应用程序
'whitenoise.runserver_nostatic'
添加到您的设置中 - 添加到您的设置.py MIDDLEWARE
'whitenoise.middleware.WhiteNoiseMiddleware'
- 添加到您的搜索中。点击以下3行
STATIC_URL = '/static/'
STATICFILES_DIRS = (str(BASE_DIR.joinpath('static')),)
STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles'))
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # new
django_heroku.settings(locals())
对于这里的最后一行,您需要安装django_heroku
(而不是django_on_heroku
,请小心(
有关更多信息,请查看:https://learndjango.com/tutorials/django-static-files.
附言:如果之后因为找不到静态文件文件夹而失败,请手动创建它。你只需要做一次,就这样了。一个空文件夹,什么都没有。