blog_django_logo.png

Django settings to store media in S3 and serve from CloudFront

python AWS Django S3 CloudFront

This assumes you've already set up an account in AWS (set up an account here) and have an S3 Bucket and CloudFront account.

Versions

This was written using Django==2.2, Python==3.8

Install Django storage middleware and activate it in our INSTALLED_APPS in settings.py

        pip install django-storages
    
        INSTALLED_APPS = [
    ...
    'storages',  # new
    ...
]
    

Let's install boto3, which is the Amazon Web Services (AWS) Software Development Kit (SDK) for Python, which allows Python developers to write software that makes use of services like Amazon S3 and Amazon EC2.

To do this

        pip install boto3
    

Add these to your settings.py file

        DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

AWS_ACCESS_KEY_ID = '############'
AWS_SECRET_ACCESS_KEY = '#######################'

AWS_STORAGE_BUCKET_NAME = 'rory-ferguson'
AWS_S3_CUSTOM_DOMAIN = '######.cloudfront.net'

CLOUDFRONT_DOMAIN = '######.cloudfront.net'
CLOUDFRONT_ID = '###########'
    

The key here is assigning the AWS_S3_CUSTOM_DOMAIN to the CloudFront domain name.

DEFAULT_FILE_STORAGE: Instructs Django storage middleware to use AWS S3 storage, which we installed above.

AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY: are obtained in the IAM portal, under Users > Security Credentials, bear in mind you can't retrieve old secret keys so generate a new one if needed.

AWS_STORAGE_BUCKET_NAME: This is the literal bucket name of the bucket you create in S3

AWS_S3_CUSTOM_DOMAIN: The URL the files are served from

In the CloudFront panel, add the S3 bucket origin domain name and path.

Some handy headers

        AWS_DEFAULT_ACL = 'public-read'
AWS_HEADERS = {
    'Expires': 'Thu, 15 Apr 2010 20:00:00 GMT',
    'Cache-Control': 'max-age=31536000',
}
    

Go ahead and read the docs for Django-Storages.