Search code examples
djangoamazon-s3boto3django-staticfilespython-django-storages

Not able to use django-storages to fetch static files


I am trying to use django storages to fetch static files for Django admin. I am facing a strange behavior that I am not able to understand clearly. I am having two different buckets, one for static files and other for some other purpose. If I comment out the AWS_S3_CUSTOM_DOMAIN keep everything else as it is (the way it is posted below), everything works. But if I uncomment AWS_S3_CUSTOM_DOMAIN and override the custom domain in my storage backend StaticStorage, it starts giving me 403. I know that I am missing something, just not able to figure out what.

settings.py

S3_BUCKET = os.environ.get('S3_BUCKET')
S3_FILE_LOCATION = os.environ.get('S3_FILE_LOCATION')

AWS_ACCESS_KEY_ID = os.environ.get('S3_STORAGE_ACCESS_KEY_ID', '')
AWS_SECRET_ACCESS_KEY = os.environ.get('S3_STORAGE_SECRET_ACCESS_KEY', '')
AWS_STORAGE_BUCKET_NAME = os.environ.get('S3_BUCKET', '')
AWS_S3_CUSTOM_DOMAIN = f"{os.environ.get('S3_BUCKET', '')}.s3.amazonaws.com"
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}
AWS_DEFAULT_ACL = None
AWS_S3_VERIFY = False
AWS_S3_USE_SSL = False

# s3 static settings
STATIC_FILE_BUCKET = os.environ.get('STATIC_FILE_BUCKET')
STATIC_LOCATION = 'static'
STATIC_S3_CUSTOM_DOMAIN = f"{os.environ.get('STATIC_FILE_BUCKET', '')}.s3.amazonaws.com"
STATIC_URL = f'https://{STATIC_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/'
STATICFILES_STORAGE = 'apps.utils.storage_backends.StaticStorage'
DEFAULT_FILE_STORAGE = 'apps.utils.storage_backends.PrivateMediaStorage'

storage_backends.py

class StaticStorage(S3Boto3Storage):
    location = 'static'
    default_acl = 'private'

    def __init__(self, *args, **kwargs):
        kwargs['bucket'] = settings.STATIC_FILE_BUCKET
        # self.custom_domain = settings.STATIC_S3_CUSTOM_DOMAIN
        super().__init__(*args, **kwargs)

Solution

  • I figured out the issue, I just needed to set custom_domain as False in my storage_backends. It then simply uses static url as set in my settings.py for static files.