Django 模板中循环的图像 html

Image for loop in Django template html

请问如何在Django中的html模板中for循环生成图片:

此代码无效:

<ul>
    Plants:
    {% for plant in plants %}
        <li> <img src="{% static 'plant_photos/{{ plant.name }}.jpg' %}"> {{ plant.name }}</li>

    {% endfor %}
 </ul>

但是如果我将这个:{{ plant.name }}.jpg 替换为这个:carrot.jpg 然后显示图像。

我在static/plant_photos中保存的所有图像,每张照片的名称都与植物名称相对应。

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)

结构:

garden_app
_templates
_static
__plant_photos
___carrot.jpg
___apple.jpg
___pear.jpg

...

我认为兴趣非常有限,但为了实现您的目标,您可以将完整的字符串从 staticfiles 传递到静态标记,如下所示:

不要使用 {% static ... %},试试这个:

{% 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>

有关更多信息,this post 可以提供帮助。