5

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?

ArKitect
  • 87
  • 3
  • 7

1 Answers1

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