I would like to ask how to generate images in for loop in html template in Django:
this code doesn't work:
<ul>
Plants:
{% for plant in plants %}
<li> <img src="{% static 'plant_photos/{{ plant.name }}.jpg' %}"> {{ plant.name }}</li>
{% endfor %}
</ul>
but if I replace this: {{ plant.name }}.jpg by this: carrot.jpg then the image is displayed.
All the images I have saved in static/plant_photos and the name of each photo correspond with name of the plant.
models.py:
class Plant(models.Model):
name = models.CharField(max_length=256)
description = models.TextField(blank=True, default='')
plant_image = models.ImageField(null=True, upload_to='static/plant_photos/', height_field=None, width_field=None, max_length=20)
class Garden(models.Model):
name = models.CharField(max_length=256)
description = models.TextField(blank=True, default='')
address = models.CharField(max_length=512)
plant = models.ManyToManyField(Plant, related_name="gardens", through="GardenPlant")
views.py:
def garden_detail(request, garden_name):
garden_id = Garden.objects.get(name=garden_name).id
garden = Garden.objects.get(id=garden_id)
plants = Plant.objects.filter(gardens__name=garden_name)
context = {
'name': garden.name,
'description': garden.description,
'address': garden.address,
'plants': plants, }
return render(request, 'garden_detail.html', context=context)
structure:
garden_app
_templates
_static
__plant_photos
___carrot.jpg
___apple.jpg
___pear.jpg
...
CodePudding user response:
I think that the interest is very limited but to achieve your goal, you can pass a full string to the static tag from staticfiles
like this :
Don't use {% static ... %}
, try this instead :
{% load staticfiles %}
<ul> Plants:
{% for plant in plants %}
{% with 'plant_photos/'|add:plant.name|add:'.jpg' as plant_photo %}
<li><img src="{% static plant_photo %}">{{ plant.name }}</li>
{% endwith %}
{% endfor %} </ul>
For more information, this post can help.