[Django]-Access ForeignKey set directly in template in Django

75๐Ÿ‘

โœ…

{% with item.itemimage_set.all|first as image %}
  <img src="{{ image.url }}" />
{% endwith %} 
๐Ÿ‘คAndrey Fedoseev

18๐Ÿ‘

Or you could add a method to your Item model:

def get_first_image(self):
    return self.itemimage_set.all()[0]

and then call this method in your template:

{{ item.get_first_image }}

Or you could use:

{{ item.itemimage_set.all.0 }}

and to get the first imageโ€™s url:

<img src="{{ item.itemimage_set.all.0.url }}">

Though if you need more flexibility (more than one picture in certain cases, etc.) itโ€™s probably best to write a little templatetag.

๐Ÿ‘คarie

9๐Ÿ‘

One possible way would be to iterate over all the ItemImages like so:

{% for item in items %}
<div>
    {{ item.name }}<br>
    {% for image in item.itemimage_set.all %}
    <img src="{{ image.image.url }}">
    {% endfor %}
</div>
{% endfor %}
๐Ÿ‘คYuval Adam

4๐Ÿ‘

This worked for me, use the related_name in your models.

models.py

class Building(models.Model):
    address  = models.CharField(max_length=200, blank=True, null=True)
    city     = models.CharField(max_length=200, blank=True, null=True)

class Space(models.Model):
    title     = models.CharField(max_length=200, blank=True, null=True)
    building  = models.ForeignKey(Building, related_name="spaces_of_this_building")

buildings.html

{% for space in building.spaces_of_this_building.all %}
  {{ space.title }}
{% endfor %}
๐Ÿ‘คBrian Sanchez

2๐Ÿ‘

If you want the first picture from set you can do:

{% for item in item.image_set.all %}

{{if forloop.first }}
<img src="{{ item.url }}">
{% endif %}

{% endfor %}

But i also love Andray solution with โ€˜withโ€™

๐Ÿ‘คzzart

Leave a comment