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

Flask预算追踪网站request.form.get()返回None问题求助

问题:Flask无法获取下拉选择的支出类别

我用Python和Flask开发预算追踪网站,记录个人支出。设置了支出类别选择区域,但用request.form.get("selected")获取用户选择的类别时返回None,存入session也无效;用request.form["selected"]会触发400错误。

HTML代码

<form action="/" method="post" enctype="multipart/form-data">
  <h3 class="h3">Your expenses</h3>
  <div class="top">
    <input type="number" class="form-control mx-auto w-auto" placeholder="$0.00" aria-describedby="button-addon2">
  </div>
  <!-- Button trigger modal -->
  <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">Add Expense</button>

  <!-- Modal -->
  <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h1 class="modal-title fs-5" id="exampleModalLabel">Category: </h1>
          <div>
            <select id="category-select" class="form-select" aria-label="Default select example">
              <option id="selected" name="selected" selected>Select type</option>
              <option id="home" name="home" value="0">Home</option>
              <option id="loans" name="loans" value="1">Loans</option>
              <option id="entertainment" name="entertainment" value="2">Entertainment</option>
              <option id="transportation" name="transportation" value="3">Transportation</option>
              <option id="other" name="other" value="5">Other</option </div>
            </select>
          </div>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <input type="number" id="amount" name="amount" class="form-control" placeholder="$0.00" aria-describedby="button-addon2" min="1">
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="submit" id="addBtn" class="btn btn-primary">Add money</button>
        </div>
      </div>
    </div>
  </div>
</form>

Python代码

@app.route("/", methods=["GET", "POST"])
@login_required
def index():
   
    if request.method == "GET":
        return render_template("index.html")
    else:
        # Get data from user input
        user_id = session["user_id"]
        date = datetime.datetime.now()

        # Check user cash
        usr_cash = db.execute("SELECT cash FROM users WHERE id = ?", user_id)[0]["cash"]

        # Check expense amount
        amount = int(request.form.get("amount"))

        # Check if user has enough money for expense
        if usr_cash < amount:
            return apology("Not enough money for this expense! Try adding more income")

        # Update user cash after expense
        updt_cash = usr_cash - amount

        # Update database
        db.execute("UPDATE users SET cash = ? WHERE id = ?", updt_cash, user_id)

        # Create transactions list
        selected = request.form.get("selected")
        
        if selected == "Home":
            db.execute("INSERT INTO category (home, user_id, date) VALUES (?, ?, ?)", amount, user_id, date)
        elif selected == "Loans":
            db.execute("INSERT INTO category (loans, user_id, date) VALUES (?, ?, ?)", amount, user_id, date)
        elif selected == "Entertainment":
            db.execute("INSERT INTO category (entertainment, user_id, date) VALUES (?, ?, ?)", amount, user_id, date)
        elif selected == "Transportation":
            db.execute("INSERT INTO category (transportation, user_id, date) VALUES (?, ?, ?)", amount, user_id, date)
        elif selected == "Other":
            db.execute("INSERT INTO category (other, user_id, date) VALUES (?, ?, ?)", amount, user_id, date)

        print(selected)

        return render_template("index.html")

解决方案

1. 核心问题:表单控件name属性设置错误

表单提交时,只有带有name属性的控件值才会被发送到后端。你的HTML中错误地给每个option添加了name,却没有给承载选项的select标签设置name,导致后端无法捕获到选择值。

2. 修复HTML代码

  • 给select标签添加name="selected"(这是后端获取值的关键)
  • 移除所有option上的name属性(完全多余)
  • 修正最后一个option的闭合错误(缺少>)
  • 移除不必要的enctype="multipart/form-data"(无文件上传需求时不需要)

修改后的HTML核心部分:

<select id="category-select" name="selected" class="form-select" aria-label="Default select example">
  <option selected>Select type</option>
  <option value="Home">Home</option>
  <option value="Loans">Loans</option>
  <option value="Entertainment">Entertainment</option>
  <option value="Transportation">Transportation</option>
  <option value="Other">Other</option>
</select>

3. 同步调整Python逻辑(可选)

如果想保留原option的数字value(如value="0"对应Home),需要修改Python中的判断逻辑:

selected = request.form.get("selected")
if selected == "0":
    db.execute("INSERT INTO category (home, user_id, date) VALUES (?, ?, ?)", amount, user_id, date)
elif selected == "1":
    db.execute("INSERT INTO category (loans, user_id, date) VALUES (?, ?, ?)", amount, user_id, date)
# 其余类别依次类推

4. 额外优化:添加默认值校验

在后端可以添加对selected的非空校验,避免用户未选择类别就提交:

selected = request.form.get("selected")
if not selected or selected == "Select type":
    return apology("Please select an expense category")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 18:43:11