【问题标题】:My Delete modalForm always delete the first object in the dataModel?(Django)我的删除模式表单总是删除数据模型中的第一个对象?(Django)
【发布时间】:2019-11-22 14:14:09
【问题描述】:

我使用引导程序创建了一个模式来删除列表视图中的用户条目,因此我不得不在模板中使用 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>

【问题讨论】:

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


    【解决方案1】:

    您为所有模态表单提供相同的 id。您应该消除歧义,例如将主键添加到您的 id,例如:

    {% for obj in patients %}
    <div class="modal fade" id="modalDelete{{ obj.pk }}" 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 %}

    作为触发按钮:

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

    【讨论】:

    • 非常感谢!顺便说一句,您知道如何将模态显示在屏幕上,因为它现在显示在绝对向上。当我点击取消或关闭按钮时它仍然没有关闭。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 2011-07-19
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多