TotuDoum
TotuDoum

Reputation: 137

how to display foreignkey image in django

Here is the problem, I'm a bit lost with foreignkey, i've seen a lot of post and i don't understand everything.
I have a item table:

class Item(models.Model):
    title = models.CharField(max_length=150)
    slug = models.SlugField(max_length=100)
    price = models.IntegerField()
    stock = models.IntegerField()
    description = models.TextField()
    image = models.ImageField(upload_to=item_file_name)

There is an image wich is the principal. On my index when I list all my item I want to see the image of each item. But when I click on the item I want to see all of the image of this item (in another view). So I've done this.

class ImageOfItem(models.Model):
    picture = models.ImageField(upload_to=item_file_name_for_image)
    item = models.ForeignKey('Item')

I don't know if it's good but it's working. I can add an item with a picture on the admin panel. And then I can add an image and attach it to the item.(it works, the best way would be to be able to upload all the image when creating the item but I prefer to start easy).
So know everything is save as I want. But I don't know how to display all the images. My view looks like this:

def view_item(request, id, slug):
    item = get_object_or_404(Item, id=id)
    return render(request, 'ecommerce/view_item.html', locals())

I don't know if I have to get images too or if django already done it. and there is no var_dump so no way to know if it's in my variable item

my template:

{{item.title}}
{{item.description}}<br>
{{item.price}}<br>
{{item.stock}}<br>

<img src="{{ item.image.url }}"><br> //principal image it works !!
{% for img in item.ImageOfItem %}
    <img src="{{ img.picture.url }}"><br> //**all the image I want to display too (but don't know how)**
{% endfor %}

all the image I want to display too (but don't know how)

Upvotes: 0

Views: 2361

Answers (1)

catavaran
catavaran

Reputation: 45575

You should follow relationship backward from Item to ImageOfItem:

{% for img in item.imageofitem_set.all %}
    <img src="{{ img.picture.url }}"><br>
{% endfor %}

Upvotes: 1

Related Questions