尝试将静态文件上传到S3时,Django一直使用错误的存储后端

时间:2020-04-09 00:12:27

标签: python django boto3 python-django-storages

更新:错误不是由django存储引起的,而是由django-heroku引起的。

看来django-heroku会覆盖一些导致此行为的变量。请在下面查看我的答案。


我一直在将S3用作其他Django应用程序的存储服务,但是对于一个新项目,Django拒绝选择正确的后端,并继续将文件放在本地文件系统中而不是上传。

确切地说,在我安装boto3并调整settings.py然后运行python manage.py collectstatic之后,该命令会将静态文件移至<my_project_path>/staticfiles,而不是开始将文件上传到S3。

这是python manage.py collectstatic的输出:

You have requested to collect static files at the destination
location as specified in your settings:

    <my_project_path>/staticfiles

This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel:

我的设置:

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

    # Vendor
    'storages',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'sass_processor',
    'crispy_forms',

    [..]
]

# static & media files
USE_S3 = config('USE_S3', cast=bool, default=True)

AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
AWS_DEFAULT_ACL = None
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET')
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}
AWS_LOCATION = 'static'

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

if USE_S3:
    MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, 'media')
    DEFAULT_FILE_STORAGE = '<my_app>.storage_backends.MediaStorage'
    STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
    STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

else:
    MEDIA_URL = '/media/'
    STATIC_URL = '/static/'
    STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'sass_processor.finders.CssFinder',
]

我的要求。txt:

...
boto3==1.11.12
botocore==1.14.15
django-storages==1.9.1
jmespath==0.9.4
s3transfer==0.3.3
...

我尝试从可以上传的其他项目中复制设置,重新检查了django-storages文档,甚至安装了boto3的确切版本等,以排除由于更新版本导致的错误,然后检查了我的{{ 1}},如果我忘记了一个有冲突的设置,但是我无法弄清楚为什么Django甚至都没有尝试上传。

非常感谢任何指针!

1 个答案:

答案 0 :(得分:1)

经过进一步的挖掘,我找到了罪魁祸首。原来django-heroku程序包导致了不良行为。

该软件包会自动设置STATIC_ROOT='/static/',从而覆盖settings.py中的AWS位置。

您可以通过在设置django-heroku时设置staticfiles=False来禁用此行为,

import django_heroku
django_heroku.settings(locals(), staticfiles=False)

我还意识到在其他已成功运行S3的应用程序中,我什至没有使用django-heroku,这引起了我的困惑,这是我以前检查中错过的设置上的一个区别。