具有多张图片的Django Modal

时间:2019-02-01 21:22:48

标签: django django-templates bootstrap-4 bootstrap-modal

我只是想让Django在模式弹出窗口中显示图像。我的问题是,如果使用多个图像,则模式弹出框中仅显示第一个图像。在用作按钮的按比例缩小的图像中,显示正确的图像。因此,我不明白这里出了什么问题。它应该是什么样?

    {% block content %}
      {% if object.image_count %}
        <div class="row">
           <div class="col-lg-12">
              {% for img in object.image_set.all %}
                {% thumbnail img.file "150x150" crop="center" as im %}
                  <!--a href='{{ img.file.url }}' data-lightbox="lightbox[{{ object.id }}]"
                     title="{{ object.title }}">
                     <img itemprop="image" src='{{ im.url }}' alt='{{ object.title }}' title='{{ object.title }}'
                                 width="{{ im.width }}" height="{{ im.height }}" class="img-rounded"/>
                     </a-->
                  <!-- image trigger modal -->
                  <a data-toggle="modal" data-target="#myModal">
                  <img src="{{ im.url }}">
                  </a>
                  <!-- Modal -->
                  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                     <div class="modal-dialog">
                        <div class="modal-content">
                           <div class="modal-header">
                              <h4 class="modal-title" id="myModalLabel">{{ object.title }}</h4>
                              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                           </div>
                           <div class="modal-body">
                              <img itemprop="image" src='{{ img.file.url }}'  class="img-rounded" style="width:100%">
                           </div>
                           <div class="modal-footer">
                              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                           </div>
                        </div>
                     </div>
                  </div>
                {% endthumbnail %}
              {% endfor %}
           </div>
        </div>
      {% endif %}
    {% endblock %}

1 个答案:

答案 0 :(得分:0)

您正在循环中创建具有相同ID属性的多个元素,这意味着所有缩略图都链接到相同的模态。用Django的内置循环计数器区分ID:

<a data-toggle="modal" data-target="#myModal{{ forloop.counter }}">
...
<div class="modal fade" id="myModal{{ forloop.counter }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

将输出#myModal1myModal2等。Django docs