Updated MEDIA_URL not reflected in ImageField url

2019-08-30 03:44发布

问题:

I'm trying to move from serving files on Amazon S3 to Amazon CloudFront, so I updated my settings.py. Previously, I had this:

S3_URL = 'http://{}.s3.amazonaws.com'.format(AWS_STORAGE_BUCKET_NAME)
STATIC_URL = S3_URL + STATIC_DIRECTORY
MEDIA_URL = S3_URL + MEDIA_DIRECTORY

I updated this as follows:

#S3_URL = 'http://{}.s3.amazonaws.com'.format(AWS_STORAGE_BUCKET_NAME)
S3_URL = 'http://d2ynhpzeiwwiom.cloudfront.net'

In the console, the settings are updated:

>>> from django.conf import settings
>>> settings.MEDIA_URL
'http://d2ynhpzeiwwiom.cloudfront.net/media/'

But not on my model's ImageField:

>>> design.image.url
'https://bucketname.s3.amazonaws.com/media/images/designs/etc/etc'

What gives? Where is the old information still stored and how do I flush it out?

回答1:

Whoops, turns out the FileField.url property doesn't use MEDIA_URL. According to the Django docs:

FieldFile.url

A read-only property to access the file’s relative URL by calling the url() method of the underlying Storage class.

In my case, the underlying storage class, was S3BotoStorage provided by django-storages. As noted by this now-deprecated fork, this was previously not supported, but can now be done by adding the following to settings.py:

AWS_S3_CUSTOM_DOMAIN = 'd2ynhpzeiwwiom.cloudfront.net'

Now it works like a charm:

>>> design.image.url
u'https://d2ynhpzeiwwiom.cloudfront.net/media/images/designs/etc/etc'