To get your access key ID and secret access key follow the steps below.
Now we need to create a S3 bucket to store our files in it.
To create S3 bucket follow the steps below:
On the opened window enter the Bucket Name and Choose the Region and click on Next.
Do Next and Next and finally click on Create Bucket. And once this is done, new bucket will be created and it will show up on the page.
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
.
First, you need to go to Heroku dashboard settings, click on your app and then click on settings tab and finally click on config vars.
Then just enter all your environment variables like AWS_ACCESS_KEY_ID
, AWS_S3_CUSTOM_DOMAIN
, AWS_SECRET_ACCESS_KEY
and etc…. by entering Key and Value and clicking on Add
button.
In config vars, add AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
from what you received after creating IAM user.
AWS_STORAGE_BUCKET_NAME
will be kodefork-assets
, in your case the name of your bucket.
AWS_S3_CUSTOM_DOMAIN
will be kodefork-assets.s3.amazonaws.com
, see carefully it’s bucket name followed by .s3.amazonaws.com
.
MEDIA_URL
will be https://kodefork-assets.s3.amazonaws.com/
, again see it is my bucket_name and then url is formed.
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.