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?
{% with item.itemimage_set.all|first as image %} <img src="{{ image.url }}" /> {% endwith %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With