You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中如何实现批量删除?通过复选框选中条目后删除所选数据

批量删除功能错误修正方案

核心错误点梳理

  • 模板侧没有包裹form表单,复选框值无法提交到后端
  • 模板内checked判断逻辑错误,将模板变量写死为字符串比较,永远不会触发选中状态
  • 删除操作使用GET请求不符合HTTP规范,存在安全风险
  • 视图侧变量名写错,且获取多个同名参数错误使用get()方法,只能拿到最后一个选中项的值

修正后模板代码

首先你需要把表格包裹在POST提交的表单内,补充CSRF防护和提交按钮:

<form method="post" action="{% url 'delete_bulk_books' %}">
  {% csrf_token %}
  <table class="layout container">
      <thead>
        <th>Name</th>
        <th>Mark</th>
      </thead>
    {% for book in books %}
      <tr>
        <td>{{ book.book_name }}</td>
        <td>
          <!-- 如果不需要回显提交后的选中状态,可直接删除后面的if判断代码 -->
          <input type="checkbox" name="marked_delete" value="{{ book.pk }}">
        </td>
      </tr>
    {% endfor %}
  </table>
  <button type="submit">批量删除选中</button>
</form>

如果你需要提交失败后保留用户选中的状态,需要从视图侧传回选中的ID列表,再将复选框的判断改为{% if book.pk|stringformat:"i" in marked_delete_list %} checked {% endif %}即可。

修正后视图代码

def delete_bulk_books(request):
    if request.method == "POST":
        # getlist才能拿到所有同名参数的取值列表
        delete_ids = request.POST.getlist('marked_delete')
        # 避免用户未选中任何内容时误删所有数据
        if delete_ids:
            Books.objects.filter(id__in=delete_ids).delete()
    return redirect("view_books")

内容的提问来源于stack exchange,提问作者fakeMake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 13:24:08