10

In a view, how can I return the MEDIA_URL for Imagefield queryset?

 2 years ago
source link: https://www.codesd.com/item/in-a-view-how-can-i-return-the-media-url-for-imagefield-queryset.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

In a view, how can I return the MEDIA_URL for Imagefield queryset?

advertisements

Assume I have the following model:

class ProductImage(models.Model):
    image = models.ImageField('Product image', null=True,blank=True)
    view = models.CharField(max_length=2, choices=VIEW_TYPES, default='FR', null=True,blank=True)
    description = models.CharField(max_length=125, blank=True, null=True)
    def __str__(self):
        return self.view + "-" + self.image.url

I have the following queryset:

allProductImages = ProductImage.objects.all()

How do I extract the MEDIA_URL + path + filename for all objects (e.g. /media/image.jpg)

here's what I have already tried (follows on from previous queryset statement): urlValues = allImages.values('image')

<QuerySet [{'image': 'greenSwatch.jpg'}, {'image': 'blueSwatch.jpg'}, {'image': '3037-outer-black.jpg'}, {'image': '3037-outer-black.png'}]

I'm trying to get the following: <QuerySet [{'image': '/media/path/greenSwatch.jpg'}, {'image': '/media/path/blueSwatch.jpg'}, {'image': '/media/path/3037-outer-black.jpg'}, {'image': '/media/path/3037-outer-black.png'}, {'image': '/media/path/3037-inner-blue.png'}, {'image': '/media/path/3037-outer-green.png'}, {'image': '/media/path/3037-outer-blue.png'}]>

Also, I know there's no upload_to parameter specified, but this is optional according to the docs for Django 1.10

I'm running Django 1.10 + Python 3.5


p.image.url gives you the full URL for the image, given p as a ProductImage instance. Since you have a queryset, you just need to iterate through; you shouldn't use values though.

allProductImages = ProductImage.objects.all()
image_urls = [p.image.url for p in allProductImages]


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK