django-storages
django-storages copied to clipboard
Media not being served from correct url
I am using django-storages for serving static and media from AWS s3,not cloudfront, static seems to work fine. Media files are uploaded to the right path, but are not served from the same url. As seen in the screenshot, static is served from aws but media is being served from the wrong url. Following are my settings:
from storages.backends.s3boto3 import S3Boto3Storage
from django.conf import settings
class MediaStorage(S3Boto3Storage):
location = settings.MEDIAFILES_LOCATION
bucket_name = 'elasticbeanstalk-ap-south-1-365959033610'
custom_domain = '{}.s3.amazonaws.com'.format(bucket_name)
file_overwrite = False
class StaticStorage(S3Boto3Storage):
location = settings.STATICFILES_LOCATION
#settings.py
AWS_STORAGE_BUCKET_NAME = 'XXXXXXXXXXXXXX'
AWS_S3_REGION_NAME = 'XXXXXXX' # e.g. us-east-2
AWS_ACCESS_KEY_ID = 'XXXXXXXXXXXXXXXXX'
AWS_SECRET_ACCESS_KEY = 'XXXXXXXXXXXXXXXXXX
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
STATICFILES_STORAGE = 'solvesto.storage_backends.StaticStorage'
DEFAULT_FILE_STORAGE = 'solvesto.storage_backends.MediaStorage'
STATICFILES_LOCATION = 'static'
MEDIAFILES_LOCATION = 'media'
STATIC_URL = '/static/'

Also, check this url: http://django-env.eba-mdj74cdp.ap-south-1.elasticbeanstalk.com/media/testimonials/Screen_Shot_2020-11-16_at_23.11.23.png The above url is invalid and correct one should have been: https://elasticbeanstalk-ap-south-1-365959033610.s3.amazonaws.com/media/testimonials/Screen_Shot_2020-11-16_at_23.11.23.png
I believe we are running into the same issue here as well. We have a bucket_name specified in a FileField and the file gets uploaded to the right bucket, but the path is saved to DB using the default s3 bucket, not our specifically named bucket in the FileField.
class Attachment(models.Model):
...
filename = models.CharField(max_length=255)
uploaded_file = models.FileField(
upload_to="attachments/",
storage=S3Boto3Storage(bucket_name=settings.AWS_ARTIFACTS_BUCKET_NAME),
)
...
from settings.py:
AWS_STORAGE_BUCKET_NAME = "bucket-static-dev"
AWS_ARTIFACTS_BUCKET_NAME = "bucket-artifacts-dev"
DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
Seems this can be fixed with the addition of custom_domain to the model, like:
class Attachment(models.Model):
...
filename = models.CharField(max_length=255)
uploaded_file = models.FileField(
upload_to="attachments/",
storage=S3Boto3Storage(
bucket_name=settings.AWS_ARTIFACTS_BUCKET_NAME,
custom_domain=settings.AWS_ARTIFACTS_CUSTOM_DOMAIN
),
)
...