Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access ForeignKey set directly in template in Django

I have this simplified model:

class Item(models.Model):     name = models.CharField(max_length=120)  class ItemImage(models.Model):     image = models.ImageField(upload_to='upload_dir')     item = models.ForeignKey(Item) 

An Item can have many ItemImages. I also have a template rendering the following data set from the view:

items = Item.objects.all() 

So now I would want to do something like this in the template:

{% for item in items %} <div>     {{ item.name }}<br>     <img src="{{ item.itemimage_set.all()[0] }}"> </div> {% endfor %} 

But obviously that's not possible. Not from the template directly, at least.

What is the proper way to get the equivalent of the first image inside the template?

like image 816
Yuval Adam Avatar asked Jun 02 '11 16:06

Yuval Adam


1 Answers

{% with item.itemimage_set.all|first as image %}   <img src="{{ image.url }}" /> {% endwith %}  
like image 200
Andrey Fedoseev Avatar answered Oct 10 '22 01:10

Andrey Fedoseev