In Django, what is the best way to construct the absolute path to an image URL when you're using a CDN to serve media files? In my case, I have a QuerySet of Movie objects, and I want to retrieve the absolute URL of the image attribute of the movie, where image is an ImageField. Is there any way to do this by using a template tag or the values() function of the QuerySet API?
Asked
Active
Viewed 8,609 times
1 Answers
7
I solve this by prefixing the url for the model field with the MEDIA_URL value from settings.py. You could create a property on the model that returns this concatenated path as whatever name you'd like.
Example:
@property
def get_absolute_image_url(self):
return '%s%s' % (MEDIA_URL, self.image.url)

Brandon Taylor
- 33,823
- 15
- 104
- 144
-
11The `image.url` will already have the media prefix on it, I believe. – nhinkle Jan 05 '14 at 08:10
-
4At the time this question was answered in 2012, the image url did not have the media prefix prepended. – Brandon Taylor Sep 19 '14 at 10:49