我的Delete modalForm总是删除dataModel中的第一个对象吗?(Django)

时间:2019-07-12 19:48:16

标签: javascript html django bootstrap-4 django-templates

我使用引导程序制作了一个模态,以删除列表视图中的用户条目,因此我不得不在模板中使用for循环进行迭代,因此它始终删除第一个对象,并且永远不会关闭。如何使每个条目的按钮唯一,使其仅删除该对象。

这是模态:

  {% for obj in patients %}

     <div class="modal fade" id="modalDelete" tabindex="-1" role="dialog" aria-labelledby="modalDelete"
  aria-hidden="true">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Delete patient!</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Are you sure you want to delete this patient?</p>
      </div>
      <div class="modal-footer">
           <form method="POST" action="{% url 'patients:patient_delete' obj.pk %}">
                            {% csrf_token %}
        <input class="btn btn-danger" value="Yes" type="submit" >
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                       </form>
      </div>
    </div>
  </div>
</div>

{% endfor %}

这是我的触发按钮:

<button type ="button" class ="btn btn-danger" data-toggle="modal" data-target="#modalDelete" >Delete</button>

1 个答案:

答案 0 :(得分:1)

您为所有模态形式赋予相同的ID。您应该消除歧义,例如,将主键添加到您的ID中,例如:

<button type ="button" class ="btn btn-danger" data-toggle="modal" data-target="#modalDelete{{ obj.pk }}">Delete</button>

并作为触发按钮:

 Cannot open self C:\WINDOWS\system32\file.exe or archive 
    C:\WINDOWS\system32\file.pkg