Get first element from many to many relationship django in template
I'm trying to get the first element from queryset which is returned by a Model Field which is a ManyToManyField
right in the template.
models.py
class CraftImage(models.Model):
image = models.ImageField(upload_to='crafts_images/', null=True)
class Craft(models.Model):
title = models.CharField(max_length=100, null=False, blank=False)
images = models.ManyToManyField(CraftImage, blank=True, related_name='craft_images')
views.py
def work_all(request):
crafts = Craft.objects.all()
context = {
'crafts': crafts,
}
template.py
{% for craft in crafts %}
<div style="background-image: url('{% static 'craft.images[0].image.url' %}');"></div>
{% endfor %}
Something like this.
I've also tried following some solutions I found which didn't work for me such as..
views.py
crafts = Craft.objects.all()
images = Craft.objects.values_list('images').first()
print(images)
context = {
'crafts': crafts,
'images': images
}
templates.py
{% for craft in crafts %}
<div style="background-image: url('{% static 'images.image.url' %}');"></div>
{% endfor %}
Solved it by using
<div style="background-image: url('{{ craft.images.all.first.image.url }}');"></div>