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

本地Flask项目删除数据库条目失败,提示URL未找到

Flask删除功能404错误修复方案

错误原因

服务器返回404是因为前端提交的删除请求URL为/delete,但后端仅定义了带ID参数的路由/delete/<int:id>,两者不匹配,导致服务器找不到对应处理逻辑。

具体修复步骤

1. 修复单条目删除功能

后端路由(确认正确,仅修正拼写错误)

当前单条删除路由逻辑正常,只需修正提示文本的拼写错误:

@app.route('/delete/<int:id>', methods=['GET','POST'])
def deleteMovement(id):
        cur = mysql.connection.cursor()
        cur.execute("DELETE FROM items WHERE id = %s", (id,))
        mysql.connection.commit()
        cur.close()
        flash('Item successfully deleted', 'success')  # 修正:sucessfully → successfully
        return redirect('/transfer')

前端页面(transfer.html)调整

把删除按钮绑定到表格每行的具体条目ID:

  1. 表头新增操作列:
<th>操作</th>
  1. 在表格循环的每一行末尾添加删除表单:
{% for items in itemDetails %}
<tr id="{{ items.id }}">
    <!-- 原有列内容保持不变 -->
    <td>{{ items[6] }}</td>
    <td><input type="checkbox" name="mycheckbox" value="{{ items.id }}"></td>
    <!-- 新增单条删除按钮 -->
    <td>
        <form action="/delete/{{ items.id }}" method="post" style="display: inline;">
            <input type="submit" value="删除" class="btn btn-sm btn-danger">
        </form>
    </td>
</tr>
{% endfor %}
  1. 删除顶部按钮容器中无效的删除表单(未绑定具体ID,无法正常工作):
<!-- 删除这段无效代码 -->
<form action="/delete/{{ assetID }}" method="post">
    <input type = "submit" value="Delete">
</form>

2. 修复批量删除功能(可选)

如果需要实现多选删除,需新增后端路由并调整前端表单结构:

后端新增批量删除路由

在__init__.py中添加:

@app.route('/delete', methods=['POST'])
def delete_batch():
    # 获取选中的条目ID列表
    selected_ids = request.form.getlist('mycheckbox')
    if not selected_ids:
        flash('请选择要删除的条目', 'error')
        return redirect('/transfer')
    
    cur = mysql.connection.cursor()
    try:
        # 批量删除SQL语句
        placeholders = ','.join(['%s'] * len(selected_ids))
        cur.execute(f"DELETE FROM items WHERE id IN ({placeholders})", selected_ids)
        mysql.connection.commit()
        flash(f'成功删除{len(selected_ids)}条条目', 'success')
    except Exception as e:
        flash(f'删除失败:{str(e)}', 'error')
    finally:
        cur.close()
    
    return redirect('/transfer')

前端调整批量删除表单结构

将整个表格包裹在底部的删除表单中,确保复选框值能被正确提交:

<h2 align="center">Asset List</h2>
<form method="POST" action="/delete">
    <table border="1">
        <!-- 表格表头和内容保持不变 -->
    </table>
    <button type="submit" class="btn btn-danger mt-3">删除选中条目</button>
</form>

3. 其他细节修复

补充/transfer路由无条目时的响应逻辑:

@app.route('/transfer')
def items():
    cur = mysql.connection.cursor()
    items = cur.execute("SELECT * FROM items")
    itemDetails = []
    if items > 0:
        itemDetails = cur.fetchall()
    cur.close()
    return render_template('transfer.html', itemDetails=itemDetails)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 21:15:06