Setup DigitalOcean spaces in django

Here I will explain how to set up DigitalOcean spaces in the django app, one of the popular products in DigitalOcean. Before you start reading this post, you are reading this post as an expert user, so I won’t explain simple points.

The first step is to install Django, gunicorn, Django-storages, and boto3 packages using pip:

pip install Django

pip install gunicorn

pip install django-storages

pip install boto3

After installing packages, we need to add them to requirements.txt:

Django==3.2.12

gunicorn==20.1.0

django-storages==1.13.2

boto3==1.26.64

Your project will likely differ from my sample if you install the latest version of these packages. Pipreq can be used to generate requirements.txt automatically.

pip install pipreqs

pipreqs your_path_address

Next, log into the DigitalOcean panel and click “Create” at the top right. Select storage and create a new one.

Set up storage according to your project’s environment requirements.

In settings.py, add “storages” to INSTALLED_APPS.

INSTALLED_APPS = [
   "storages",
]

Insert the following code inside settings.py:

AWS_ACCESS_KEY_ID = 'key_id'
AWS_SECRET_ACCESS_KEY = 'access_key'
AWS_STORAGE_BUCKET_NAME = 'bucket_name'
AWS_DEFAULT_ACL = 'public-read' 
AWS_S3_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com'
AWS_S3_OBJECT_PARAMETERS = {
   'CacheControl': 'max-age=86400'
}
AWS_S3_REGION_NAME = "nyc3"

AWS_STATIC_LOCATION = 'static/'
STATIC_URL = '%s/%s' % (AWS_S3_ENDPOINT_URL, AWS_STATIC_LOCATION)
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

The prefix AWS is in the top code, which makes you wonder why we use the digital ocean for our storage, but you use AWS. This method can be used in apache libcloud, azure storage, digital ocean, Backblaze B2, DropBox, and Google cloud storage, according to django-storage documentation.

Create a new file in the same directory as settings.py, name it “storage_backends.py,” and paste the following code into it:

from django.conf import settings
   from storages.backends.s3boto3 import S3Boto3Storage


class StaticStorage(S3Boto3Storage):
   location = 'static'
   default_acl = 'public-read'


class MediaStorage(S3Boto3Storage):
   bucket_name = 'media'
   location = ''

You can change the name of your static and media directories inside your storage by editing the top code.

Then add the following code to settings.py.

AWS_MEDIA_LOCATION = 'media/'
PUBLIC_MEDIA_LOCATION = 'media'
MEDIA_URL = '%s%s' % (AWS_S3_ENDPOINT_URL, AWS_MEDIA_LOCATION)
DEFAULT_FILE_STORAGE = 'django_project.storage_backends.MediaStorage'

Then, if you’ve followed the instructions above, you can run the “python manage.py collect static” command. After the order is run, go to your storage area and see what files are inside.

Done.