在标记为重复之前,请注意我已经检查了所有类似的问题,但它并没有解决我的问题。我已经将我的 Django 应用程序部署在 Heroku 上的一个模板中,在该模板中我引用了一个 min.js 文件,它引发了这个有问题的错误。
我的基本目录结构是这样的:
myapp
mysite
dictionary
static
jquery.twbsPaginationAlt.min.js
staticfiles
设置.py:
STATIC_URL = '/static/'
# STATIC_ROOT = [os.path.join(BASE_DIR, 'staticfiles'), os.path.join(BASE_DIR, 'static/fonts')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
if DEBUG:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'mysite/static'), os.path.join(BASE_DIR, 'static/')]
import django_heroku
# handles staticfiles, database url, and secret key, can be overwritten as needed
django_heroku.settings(locals(), secret_key=False, logging=False)
所以最初如果 STATICFILES_DIRS 有任何值,我会FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_6f3eb879/mysite/static'
在 heroku 上运行 collectstatic 时出错。但是,如果未设置,则我的开发环境中的字体无法正确加载(我在基本级别的静态文件夹中也有字体)。
这就是我在问题模板中引用 js 文件的方式,它在 dev 上运行良好:
<script src='{% static 'jquery.twbsPaginationAlt.min.js' %}'></script>
为方便起见,这里是 django-heroku 在静态文件方面所做的:
logger.info('Applying Heroku Staticfiles configuration to Django settings.')
config['STATIC_ROOT'] = os.path.join(config['BASE_DIR'], 'staticfiles')
config['STATIC_URL'] = '/static/'
# Ensure STATIC_ROOT exists.
os.makedirs(config['STATIC_ROOT'], exist_ok=True)
# Insert Whitenoise Middleware.
try:
config['MIDDLEWARE_CLASSES'] = tuple(['whitenoise.middleware.WhiteNoiseMiddleware'] + list(config['MIDDLEWARE_CLASSES']))
except KeyError:
config['MIDDLEWARE'] = tuple(['whitenoise.middleware.WhiteNoiseMiddleware'] + list(config['MIDDLEWARE']))
# Enable GZip.
config['STATICFILES_STORAGE'] = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
(来自https://github.com/heroku/django-heroku/blob/master/django_heroku/core.py)
编辑:为了解决这个问题,我不得不停止使用 django heroku,将我的 STATICFILES_STORAGE 变量更改为 whitenoise.storage.CompressedStaticFilesStorage ,并通过检查日志以查看 GET 请求的路径来重新组织我保存一些静态文件的位置. 根据我看到的其他 stackoverflow 帖子,白噪声似乎非常不完美,它始终错过根目录中的“静态/”文件。此外,由于 Django 非常依赖模板中的“静态”关键字,而这在 .css 文件中不可用,因此解决将静态文件放入 css 文件(例如字体)的唯一方法是反复试验不同的路径。