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

如何在Django的HTML模板中实现无刷新删除QuerySet条目

Django无刷新删除列表条目实现方案

现有代码存在的问题

  • urls.py中路径参数名trans_num和视图函数接收的参数trans_id不匹配,请求会触发参数错误
  • 视图函数没有做登录校验、异常捕获,查询不存在的交易ID会抛出500错误,且冗余查询了User表
  • 前端fetch请求未携带Django要求的CSRF令牌,会触发403 Forbidden错误
  • 请求方法使用PUT不符合删除操作的语义,且未做请求结果校验,无论删除是否成功都会隐藏条目,逻辑不合理
  • 仅设置display: none只是隐藏元素,没有从DOM中移除,会残留无用节点

修正后的代码实现

1. urls.py 配置

统一路径参数名和视图参数名:

path("del_trans/<int:trans_id>", views.delete_transaction, name="delete_transaction")

2. views.py 逻辑优化

增加登录校验、异常捕获,简化查询逻辑:

from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required

@login_required
def delete_transaction(request, trans_id):
    # 直接查询当前用户对应的交易,不存在则返回404
    transaction = get_object_or_404(Transaction, ruser=request.user, id=trans_id)
    transaction.delete()
    return HttpResponse(status=204)

3. 前端JS逻辑优化

添加CSRF令牌获取逻辑,校验请求结果,成功后再移除对应DOM节点:

// Django官方推荐的CSRF Token获取方法
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
const csrftoken = getCookie('csrftoken');

function delete_trans(id) {
    fetch(`/del_trans/${id}`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': csrftoken,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            trans_id: id
        })
    }).then(response => {
        if (response.ok) {
            // 直接从DOM中移除对应行
            document.querySelector(`#trans-${id}`).remove();
        } else {
            alert('删除失败,请刷新页面后重试');
        }
    }).catch(error => {
        console.error('删除错误:', error);
        alert('删除失败,请检查网络连接');
    });
}

4. 模板代码(可选优化)

可以直接给按钮加样式,减少嵌套标签,原有代码也可正常运行:

<tr id="trans-{{t.id}}">
    <td>{{ t.name }}</td>
    <td>
        <button 
            class="btn" 
            onclick="delete_trans({{t.id}})"
            style="cursor:pointer;color:blue;text-decoration:underline;border:none;background:none;"
        >
            Delete
        </button>
    </td>
</tr>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:36:00