Heroku Django应用未加载静态文件(未找到404)

Tin*_*yik 2 python deployment django heroku

我一直在尝试将Django应用程序部署到heroku上。但是,它无法获取静态文件。我collecstatic在heroku上运行,static应用程序的根目录中有一个包含正确文件的文件夹: ~/static/rest_framework/css/bootstrap.min.css

Settings.py:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Run Code Online (Sandbox Code Playgroud)

卷曲:

curl 'https://xxx.herokuapp.com/static/rest_framework/css/bootstrap.min.css' \
-XGET \
-H 'Referer: https://xxx.herokuapp.com/users/login' \
-H 'Accept: text/css,*/*;q=0.1' \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7'
Run Code Online (Sandbox Code Playgroud)

lmi*_*asf 6

我花了几个小时才弄清楚这一点。@VipinMohan 解决方案适用于白噪声<4。但是,在版本 4+ 中,WhiteNoise 删除了一些在之前的主要版本中已弃用的选项。为了记录,我使用的是 Django 2.1。

文档

WhiteNoise 中间件应该直接放在 Django SecurityMiddleware 之后(如果你正在使用它)和所有其他中间件之前。

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

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
     # the next line of code is the one that solved my problems
    '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'
]
Run Code Online (Sandbox Code Playgroud)

请注意所提供链接部分中的注意事项。

您可能会发现其他第三方中间件建议它应该在中间件列表的顶部获得最高优先级。除非您完全了解正在发生的事情,否则您应该忽略此建议并始终将 WhiteNoiseMiddleware 置于其他中间件之上


Vip*_*han 5

Django不支持在生产环境中提供静态文件。但是,出色的WhiteNoise项目可以集成到您的Django应用程序中,并且正是出于这个目的而设计的。

pip install whitenoise    
Run Code Online (Sandbox Code Playgroud)

将whitenoise添加到您的requirements.txt在app / wsgi.py中添加此代码

from whitenoise.django import DjangoWhiteNoise
application = DjangoWhiteNoise(application)
Run Code Online (Sandbox Code Playgroud)