I am working on a Django project that includes user registration with the ability to upload a profile image. I intend to store these images, along with static files, in Digital Ocean Spaces, which is similar to an AWS S3 bucket. Initially, I configured Nginx to serve static files, and it worked well. However, when attempting to switch to Digital Ocean Spaces for production and configure both static and media files, I encountered difficulties.
Due to security concerns and the need for serving media files, I opted to use Digital Ocean Spaces. However, after setting up django-storages and boto3, I encountered a ‘403 Permission Denied’ error when accessing the static file’s URL generated by the server.
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
os.path.join(BASE_DIR, "media/static"),
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
MEDIAFILES_DIRS = [
os.path.join(BASE_DIR, "media")
]
AWS_ACCESS_KEY_ID = os.getenv("access_id")
AWS_SECRET_ACCESS_KEY =os.getenv("secret_key")
AWS_STORAGE_BUCKET_NAME ="taskitly2"
AWS_DEFAULT_ACL = 'public-read'
AWS_S3_ENDPOINT_URL = "https://taskitly2.nyc3.digitaloceanspaces.com"
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400'
}
AWS_STATIC_LOCATION = 'static'
STATIC_URL = '%s/%s' % (AWS_S3_ENDPOINT_URL, AWS_STATIC_LOCATION)
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_MEDIA_LOCATION = 'media'
PUBLIC_MEDIA_LOCATION = 'media'
MEDIA_URL = '%s%s' % (AWS_S3_ENDPOINT_URL, AWS_MEDIA_LOCATION)
DEFAULT_FILE_STORAGE = 'chat.backends.MediaStorage'
"""STORAGES = {
"default": {
"BACKEND": "storages.backends.s3.S3Storage",
"OPTIONS":{
"bucket_name": AWS_STORAGE_BUCKET_NAME,
},
},
"staticfiles":{
"BACKEND": "storages.backends.s3.S3Storage",
},
}"""
here’s the backend.py file:
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 = ''