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

如何解决Flask待办应用中url_for绑定按钮的404错误?

排查Flask待办应用“添加待办”按钮404错误

核心问题分析

点击“添加待办”按钮触发404,说明请求路径无法匹配app.py中定义的路由,主要排查方向如下:

1. 主页(home.html)按钮跳转链接错误

这是最可能的原因,你未提供home.html代码,需检查按钮跳转逻辑:

  • 若使用<a>标签跳转,确认href属性是否正确:
    • 错误示例:href="/add_todo"(路由定义为/add,而非/add_todo)
    • 错误示例:href="{{ url_for('add') }}"(视图函数名为add_todo,而非add)
  • 正确写法:
    <a href="{{ url_for('add_todo') }}">添加待办</a>
    
    或直接写固定路径:
    <a href="/add">添加待办</a>
    

2. 路由定义中的HTML转义字符问题(需修正,避免后续功能故障)

你的app.py中所有带参数的路由误用了HTML转义字符&lt;代替<,比如:

@app.route('/todos/mark_complete/&lt;int:todo_id&gt;')

这会导致标记完成、编辑、删除等功能后续也触发404,需统一修正为:

@app.route('/todos/mark_complete/<int:todo_id>')
@app.route('/todos/mark_incomplete/<int:todo_id>')
@app.route('/todos/edit/<int:todo_id>', methods=['GET', 'POST'])
@app.route('/todos/delete/<int:todo_id>')

3. 验证add路由的可访问性

直接在浏览器地址栏输入http://localhost:5000/add:

  • 若能打开添加页面,说明路由本身正常,问题出在主页按钮链接
  • 若仍返回404,检查Flask应用是否正常启动、add_todo视图函数是否未被注释或遗漏

修正后的关键代码片段

修正后的带参数路由(app.py)

@app.route('/todos/mark_complete/<int:todo_id>')
def mark_complete(todo_id):
    todo = Todo.query.get_or_404(todo_id)
    todo.status = 'Completed'
    db.session.commit()
    return redirect(url_for('todos'))

@app.route('/todos/mark_incomplete/<int:todo_id>')
def mark_incomplete(todo_id):
    todo = Todo.query.get_or_404(todo_id)
    todo.status = 'Incomplete'
    db.session.commit()
    return redirect(url_for('todos'))

@app.route('/todos/edit/<int:todo_id>', methods=['GET', 'POST'])
def edit(todo_id):
    todo = Todo.query.get_or_404(todo_id)

    if request.method == 'POST':
        todo.description = request.form['description']
        db.session.commit()
        return redirect(url_for('todos'))

    return render_template('edit.html', todo=todo)

@app.route('/todos/delete/<int:todo_id>')
def delete(todo_id):
    todo = Todo.query.get_or_404(todo_id)
    db.session.delete(todo)
    db.session.commit()
    return redirect(url_for('todos'))

主页正确的添加按钮示例(home.html)

<!DOCTYPE html>
<html>
<head>
  <title>Home</title>
</head>
<body>
  <h1>待办事项应用</h1>
  <a href="{{ url_for('add_todo') }}">添加待办</a>
  <br>
  <a href="{{ url_for('todos') }}">查看所有待办</a>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 10:50:00