Store Django media files in S3

Create IAM User & Get AWS Access Keys

To get your access key ID and secret access key follow the steps below.

create_user.png

add_user_aws.png

permissions_aws.png

create_aws_user.png

credentials_aws.png


Now we need to create a S3 bucket to store our files in it.

Create S3 Bucket

To create S3 bucket follow the steps below:

S3_console.png

Note: Here I have already created my bucket and am going to make use of my S3 bucket kodefork-assets.


Now, as IAM user is created and we have access keys from AWS and we have also created S3 bucket. Let’s store these keys in Heroku config vars so that we can access it using environment variables.

Saving Environment variables to Heroku

heroku_config_vars_kodefork_1.png heroku_config_vars_kodefork_2.png

settings.py

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID", "") 
AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY", "")
AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME", "")
AWS_QUERYSTRING_AUTH = False 
AWS_S3_CUSTOM_DOMAIN = os.environ.get("AWS_S3_CUSTOM_DOMAIN", "")
MEDIA_ROOT = os.environ.get("MEDIA_URL", "")
MEDIA_URL = '/media/'

Now just update your code to heroku and its should work and file should be stored in your S3 bucket.