---
# System prepended metadata

title: Using AWS to Store the Static and Media Files From

---

# Using AWS to Store the Static and Media Files From 

## 1. Setting Up S3 bucket Configuration ON AWS

- **Head over to [AWS Sign in Link](https://console.aws.amazon.com/console/home?nc2=h_ct&src=header-signin)**

- **Select S3 From The Search Bar**


![](https://i.imgur.com/9zL5dHC.png)


- **Create a New Bucket With A Name**
![](https://i.imgur.com/tqPP5uj.png)


- **Give Bucket A Name**
![](https://i.imgur.com/n1tjGaw.png)

    **Note Down:**
    - Bucket Name
    - Region

- **Unselect Block All Public Access**
![](https://i.imgur.com/weHUSAU.png)

> Caveats: Do not Allow Public Access By Default. This is just for a demo purpose.

## 2. Configuring IAM Roles and User For the Bucket

> At this step we'll create a user and a **AWS_ACCESS_KEY** and **AWS_ACCESS_KEY_SECRET** to be used with our django app

- **Head over to IAM Roles Management Page and select the Users**

![](https://i.imgur.com/030AtnJ.png)

![](https://i.imgur.com/dJHAQPv.png)


On the very next screen after creating a user, you'll be prompted with what access should be provided to this user. Select the One With **AmazonS3FullAccess** then procede to next screen and create a user

![](https://i.imgur.com/3INrIZr.png)


To create an access credentials for the user Head Over to the Users Screen and select the user created.

![](https://i.imgur.com/pKIMQ28.png)

On the next screen select **Security Credentials** 

![](https://i.imgur.com/OQWApo6.png)


At the bottom of a page, you can find an option to create an ACCESS KEYs for the user as:

![](https://i.imgur.com/BdM1EIP.png)

On the next screen, you'll be prompted with option to describe how would you intend to use the user's credentials for:

Select Local Code as we are going to access the objects on buckets programatically.

![](https://i.imgur.com/kmAKmwe.png)

Then provide a Tag Value to Identify the Resource Cost and Access Details for the Bucket.

Copy the Access Keys from this screen

![](https://i.imgur.com/f6Dovxn.png)

So far We created a user and the necessay credentials to use in our django app


```js
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_STORAGE_BUCKET_NAME=
AWS_S3_REGION_NAME=
```

## 3. Setting Up S3 storage on Django App

**Setting Up [django-storages](https://django-storages.readthedocs.io/en/latest/):**

- Insall django storages and boto3: ``pip install django-storages boto3 boto3 botocore``

- Add ``storages`` to the installed app.

```python
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    # libraries
    "storages",
]
```

- Replace the settings for Staticfiles and Media files with the code below.

```python
if not DEBUG:
    # aws settings
    AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID')
    AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY')
    AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME')
    AWS_S3_REGION_NAME = os.getenv('AWS_S3_REGION_NAME')
    AWS_DEFAULT_ACL = None
    AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
    AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
    # s3 static settings
    STATIC_LOCATION = 'static'
    STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/'
    STATICFILES_STORAGE = '<app>.storage_backends.StaticStorage'
    # s3 public media settings
    PUBLIC_MEDIA_LOCATION = 'media'
    MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/'
    DEFAULT_FILE_STORAGE = '<app>.storage_backends.PublicMediaStorage'
    # s3 private media settings
    PRIVATE_MEDIA_LOCATION = 'private'
    PRIVATE_FILE_STORAGE = '<app>.storage_backends.PrivateMediaStorage'
else:
    STATIC_URL = '/staticfiles/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
    MEDIA_URL = '/mediafiles/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')

STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
```

**Note:** Make sure that all the variables are loaded from the environment variables

What we are doing with above configuration is, if it's not a debug mode, we'll override the default storage settings to use the storage with S3 bucket. Your .env file should look like below

```env
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_STORAGE_BUCKET_NAME=
AWS_S3_REGION_NAME=
```

**Configuring Custom Backends for Static Storage and Public and Private Media Files**

- **<app_name>/storage_backends.py**
```pthon
from storages.backends.s3boto3 import S3Boto3Storage


class StaticStorage(S3Boto3Storage):
    """Static files configuration backend"""
    location = 'static'
    default_acl = 'public-read'


class PublicMediaStorage(S3Boto3Storage):
    """COnfiguration for public media files"""
    location = 'media'
    default_acl = 'public-read'
    file_overwrite = False


class PrivateMediaStorage(S3Boto3Storage):
    """COnfiguration for pricate media files"""
    location = 'private'
    default_acl = 'private'
    file_overwrite = False
    custom_domain = False

```


## 4. Testing
- Try Running ``python manage.py collectstatic`` command rom your terminal. If this succeds, then you should be able to see the static directory on the bucket we created.

![](https://i.imgur.com/wqW7JNE.png)

