I am working on a django project v5.1 and as always I use digitalocean spaces for my static and media files.
Here is the default configuration I always use:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Our apps
...,
...,
...,
...,
# Third party apps
'storages',
]
# DigitalOcean Spaces Configuration
AWS_ACCESS_KEY_ID = os.getenv('DO_SPACE_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.getenv('DO_SPACE_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.getenv('DO_SPACE_BUCKET_NAME')
AWS_S3_ENDPOINT_URL = f"https://{os.getenv('DO_SPACE_BUCKET_NAME')}.{os.getenv('DO_SPACE_REGION')}.digitaloceanspaces.com"
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400', # Cache static files for 1 day
}
# Static and Media Files Settings
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
# Static and Media URL
STATIC_URL = f"{AWS_S3_ENDPOINT_URL}/static/"
MEDIA_URL = f"{AWS_S3_ENDPOINT_URL}/media/"
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# Optional configurations to prevent overwrite of files with the same name
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
But this time I am running into problems.
Usually I do not define STATIC_ROOT
as I am using Boto3, but now it is giving me this error if I do not define it when I run collectstatic:
django.core.exceptions.ImproperlyConfigured:
You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.
But when I do include it, it collects static files in the staticfiles folder I defined, instead of uploading to digitalocean spaces.
I do not know if there is a change in Django 5, but I did try testing the S3 uploading by going to the django shell:
from storages.backends.s3boto3 import S3Boto3Storage
from django.core.files.base import ContentFile
storage.save('testfile.txt', ContentFile('This is a test file for DigitalOcean Spaces'))
And the file is well uploaded to my spaces bucket.
What seems to be the issue? Is there any one who has had this case in a most recent version of Django?
PS: I'm using Digitalocean for the database and spaces, and railway.app for deploying the app.
After many research efforts I finally found the issue. It was indeed because of the version of Django.
If you are running Django <= 4.2: You will use these 2 lines:
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage'
If you are running Django > 4.2: You will use these lines:
STORAGES = {
"default": {
"BACKEND": "storages.backends.s3boto3.S3Boto3Storage",
},
"staticfiles" : {
"BACKEND": "storages.backends.s3boto3.S3Boto3Storage",
},
}
Also you need to get rid of STATIC_ROOT and MEDIA_ROOT definitions.