Django 1.11 + Amazon S3 for collectstatic

时间:2018-05-22 07:20:50

标签: django amazon-s3 django-admin django-staticfiles django-settings

我刚尝试在eu-central-1上使用Amazon S3在生产中提供我的静态文件。我使用的是Elastic Beanstalk和Django 1.11。此外,我使用boto3和包Django Storages。我的问题是即使collectstatic工作并且文件现在在S3存储桶中,Django Admin仍然不使用静态文件。

对于上下文,让我给你我使用的设置:

import os

from django.core.exceptions import ImproperlyConfigured

# Static files (CSS, JavaScript, Images)

STATICFILES_DIRS = [BASE_DIR.parent / 'myproject' / 'static']

INSTALLED_APPS += ['storages', ]


def get_env_variable(var_name):
    """Get the environment variable or return exception."""
    try:
        return os.environ[var_name]
    except KeyError:
        error_msg = 'Set the {} environment variable'.format(var_name)
        raise ImproperlyConfigured(error_msg)


AWS_ACCESS_KEY_ID = get_env_variable("ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = get_env_variable("SECRET_ACCESS_KEY")
AWS_S3_SIGNATURE_VERSION = 's3v4'
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}
AWS_STORAGE_BUCKET_NAME = get_env_variable("BUCKET_NAME")
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME
AWS_LOCATION = 'static'

STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
STATICFILES_STORAGE = 'config.settings.aws.utils.StaticRootS3BotoStorage'

DEFAULT_FILE_STORAGE = 'config.settings.aws.utils.MediaRootS3BotoStorage'
MEDIA_URL = 'https://%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME
MEDIA_ROOT = MEDIA_URL

ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
S3_USE_SIGV4 = True

这些是设置,这里是我写的utils函数:

from storages.backends.s3boto3 import S3Boto3Storage


def StaticRootS3BotoStorage(): return S3Boto3Storage(location='static')


def MediaRootS3BotoStorage(): return S3Boto3Storage(location='media')

有谁知道出了什么问题?为什么收集静态工作,但Django Admin没有应用css和javascript?

1 个答案:

答案 0 :(得分:1)

我太过分了'/'。

我刚刚更正了以下一行:

AWS_S3_CUSTOM_DOMAIN = '%s.s3.eu-central-1.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

现在它有效。