[Solved]-Django Storages using s3boto ignoring MEDIA_URL

6πŸ‘

βœ…

I struck the same issue when attempting to use the Imgix CDN for my S3 media (I suspect we’re both using the same tutorial based on your use of the custom_storages.py override).

Here is an abridged version of the S3BotoStorage class in the django-storages framework. This excerpt highlights the important properties and methods for this issue, namely the custom-domain property.

class S3BotoStorage(Storage):
    location = setting('AWS_LOCATION', '')
    custom_domain = setting('AWS_S3_CUSTOM_DOMAIN')

    def url(self, name, headers=None, response_headers=None, expire=None):
        # Preserve the trailing slash after normalizing the path.
        name = self._normalize_name(self._clean_name(name))
        if self.custom_domain:
            return "%s//%s/%s" % (self.url_protocol, self.custom_domain, filepath_to_uri(name))

As you can see in the url method, a URL is generated to override the STATIC_URL and MEDIA_URL Django settings. Currently the domain of the URL is created with the AWS_S3_CUSTOM_DOMAIN setting, which is why you continue to see the static S3 URL for media files.

So first, in your Django settings file, add a setting describing your CDN’s domain.

IMGIX_DOMAIN = 'example.imgix.net'

Then, similar to the override of the location property, add an override to the custom_domain property in your MediaStorage class.

class MediaStorage(S3BotoStorage):
    location = settings.MEDIAFILES_LOCATION
    custom_domain = settings.IMGIX_DOMAIN

Now the final URL to your media files should begin with your CDN’s domain, followed by the relative path to your file on the S3 bucket.

πŸ‘€Alex

1πŸ‘

If you are serving static media from an S3 bucket, you must use an absolute URL, since the media is being served from a wholly different server.

πŸ‘€contracode

Leave a comment