pythondjangodjango-models

Django I can't access the Image.url of the ImageField object


Hey im new in django and Im playing with uploading and showing images here. I have a model product :

class Product(models.Model):
title = models.CharField("Title",max_length=50)
description = models.CharField("Description",max_length=200)
active = models.BooleanField("Active",default=False)
price = models.IntegerField("Price",default=0)
stock = models.IntegerField("Stock",default=0)
discount = models.IntegerField("Discount",default=0)
date_created = models.DateTimeField("Date Created",auto_now_add=True)
image = models.ImageField(null=True,blank=True ,upload_to="images/product/")

def __str__(self):
    return self.title

when Im retrieving this model using Product.objects.all(), and do

for prod in products :
    print(prod.image.url)

it returns error : The 'image' attribute has no file associated with it. but when im doing single query : Products.object.get(pk=5), I can access the image.url. I wonder why this happens tho. My english is bad so I hope I delivers it well.


Solution

  • As the error says, .image is None/NULL in that case, so there is no file attached to it, and therefore no url either.

    You can check if there is an image attached to it, with:

    for prod in products:
        if prod.image:
            print(prod.image.url)

    Or filter in the database:

    products = Product.objects.filter(image__isnull=False)
    for prod in products:
        print(prod.image.url)