Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a list of absolute image URLs from a Django QuerySet?

Tags:

django

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?

like image 681
ArKitect Avatar asked Feb 22 '12 02:02

ArKitect


1 Answers

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)
like image 74
Brandon Avatar answered Nov 14 '22 23:11

Brandon