我有 Django 应用程序,我想从 AWS s3 存储桶提供静态和媒体文件,但是在配置之后,只有媒体文件从 s3 提供,静态文件在本地提供。当我收集静态时,所有静态文件都收集在本地 staticfiles 文件夹中。没有文件发送到 AWS s3 存储桶。我不得不手动将它们复制到 s3。
我使用 Django==2.1.4,boto3==1.18.3,django-storages==1.11.1
下面我展示了 settings.py 中的配置(删除了一些不相关的部分,并评论了我尝试过的 STATIC_URL 和 MEDIA_URL 值)我尝试了例如本主题Django and S3 Bucket AWS Admin Static files中建议的内容。
import os
from decouple import config
import django_heroku
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
ALLOWED_HOSTS = ['yogahouse-ap.herokuapp.com']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core',
'storages',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'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',
]
ROOT_URLCONF = 'yogahouse.urls'
IMAGEKIT_URL = config('IMAGEKIT_URL')
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
AWS_S3_REGION_NAME = 'eu-central-1'
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage'
AWS_STATIC_LOCATION = 'static'
DEFAULT_FILE_STORAGE = 'yogahouse.storages.MediaStorage'
AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com"
AWS_IS_GZIPPED = True
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# STATIC_URL = f"{IMAGEKIT_URL}/static/"
# STATIC_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/static/"
MEDIA_URL = '/media/'
# MEDIA_URL = f"{IMAGEKIT_URL}/media/"
# MEDIA_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
django_heroku.settings(locals())
瑜伽屋.storages.py:
from storages.backends.s3boto3 import S3Boto3Storage
class MediaStorage(S3Boto3Storage):
location = 'media'
file_overwrite = False
class StaticStorage(S3Boto3Storage):
location = 'static'
file_overwrite = False