Amazon S3 bucket for storing media files of django app on heroku

Amazon S3 bucket for storing media files of django app on heroku

Dec. 9, 2017
6 minutes read time
0 likes
4 comments
1476 times viewed


header image

Description

Heroku only saves the static files and deletes the media files on refresh of dyno which occurs every 30 minutes. So, we need to store media files to some other location, here we are going to use Amazon Web Services. We are going to make use of Amazon S3 bucket as default media storage.

Content

To use aws resources you first need to create and IAM user.

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.



We are done



Like this post

0   Like


Share this post on

Google Plus LinkedIn


About the author




Join the discussion

Nothing to preview

Post Comment



Comments


Shubham Nayak
3 months, 1 week ago

can you help me to store media file in s3

Astik Anand
2 months ago

Yeah Tell me what’s the problem ?


Shamrose Makandar
9 months, 1 week ago

Hi Astik,

I have followed your tutorial on Django and Amazon S3 to upload the media and static files to Amazon S3 bucket, however I am unable to upload those files, Maybe I am missing some steps can you help me resolve the issue.

Thanks,
Shamrose

Shubham Nayak
3 months, 1 week ago

bro your problem solve or not