Disclaimer: This article assumes that the reader is already familiar with django framework and can perform the basic functions of django and has some hands-on experience with AWS as well.
Django is a great framework to build web backends fast and we generally start the development by simply storing everything including static and media files on the development environment itself, be it your local machine or a development server on the cloud.
But, as your project grows bigger, these files can get costly to store on the server itself and it is also not recommended to do this, especially for static web applications. So, for this, you can use cloud storage like Amazon S3 buckets or any equivalent on other cloud services. We will be covering only S3 buckets for now. So, let’s just get started with it:
- First, you need to install django-storages and boto3 using this command:
pip3 install django-storages
pip3 install boto3
2. In your settings.py file, set these two variables:
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'AWS_STORAGE_BUCKET_NAME = <your-s3-bucket-name>
The first one is for setting S3 as your file storage and the second one is for your python3 manage.py collectstatic to automatically put the static files in S3.
You’ll also need to specify your s3 bucket name where you want to serve your files from.
3. IAM setup:
The above configurations won’t work unless the server or your local machine has the required permissions to access the s3 bucket. Here is a sample IAM policy required for this.
You can also change the Principal to the ARN of your ec2 instance (if you are using EC2 instance or Elastic beanstalk as your servers)
One last thing you need to do is to uncheck the block all public access settings in your bucket permissions. This won’t make the bucket public, our Django application will only use pre-signed URLs for serving files.
If you are using EC2 instance as your server (which is likely for most of the cases), you can directly use an IAM instance profile by just creating a service role for EC2 with the above policy and attach it to the instance. That way, you won’t have to specify the AWS access key and secret key in your settings.py file. If you are going with the latter approach, you need to set the following configuration in your settings.py file as well:
AWS_ACCESS_KEY_ID = <access key>
AWS_SECRET_ACCESS_KEY = <secret key>
This worked well for me except the fact that I wasn’t able to push the existing media files that were uploaded from my app using the python3 manage.py collectstatic command. I will surely post about this issue if I find a solution for that as well.