0
votes

Say I have an image model with a many to one relationship to a product model as shown below:

   class Image(models.Model):
         product = ForeignKey(Product,on_delete=models.CASCADE,
        related_name='images'
        )
         original = ImageField(ulpoad_to='img/')
   
   class Product(models.Model):
        title = CharField(max_length=120)
        
        def get_images(self):
            return self.images.all()
       
        def get_primary_image(self):
            #return the first uploaded image in the queryset
            images = self.get_images()
            return images[0]

When trying to access {{product.get_primary_image.url}} on an image tag in a template it outputs an IndexError instead of the image, even after I add a couple more images to the database I still get the index error. Where could I be going wrong? Please help I'm still a newbie at this.

2

2 Answers

0
votes

You might have an empty images so you can't get images[0] you can use this code:

def get_primary_image(self):
    return self.get_images().first()

you will get None if there are no images in your list

1
votes

As stated above, you need to use .first().

Additionally, your function calls the Image object, not the "original" field so you'll probably need to call it with {{ product.get_primary_image.original.url }}.