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
- [Django]-Apache or Nginx to serve Django applications?
- [Django]-Pycharm error Django is not importable in this environment
- [Django]-Nginx doesn't serve static
9๐
One possible way would be to iterate over all the ItemImage
s 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
- [Django]-How to get URL of current page, including parameters, in a template?
- [Django]-Can I make STATICFILES_DIR same as STATIC_ROOT in Django 1.3?
- [Django]-Django database query: How to get object by id?
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
- [Django]-Allowing RabbitMQ-Server Connections
- [Django]-Django variable in base.html
- [Django]-Django Rest Framework โ APIView Pagination
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
- [Django]-Django and Middleware which uses request.user is always Anonymous
- [Django]-Django return redirect() with parameters
- [Django]-What is the default order of a list returned from a Django filter call?
Source:stackexchange.com