无法在 Flask 中使用 Jinja 传递变量

Can't pass a variable with Jinja in Flask

表单的操作将输入发送到名为 soldfor 的路由。我正在尝试将变量 ID 传递给 soldfor。当我点击提交按钮时,出现此错误:

TypeError: soldfor() takes exactly 1 argument (0 given)

渲染register_results.html:

return render_template('register_results.html', results=results, ID=ID)

register_results.html:

<form role="form" method="POST" action="{{ url_for('soldfor', ID={{ ID }}) }}">
      <div class="input-group">
        <input type="number" class="form-control" placeholder="Sold For" autocomplete="off" name="soldfor">
          <span class="input-group-btn">
            <button class="btn btn-default" name="soldfor" value="soldfor" type="submit">Sell!</button>
        </span>
      </div>
  </form>

售出路线:

@app.route("/soldfor", methods=["POST"])
def soldfor(ID):

    soldfor = request.form['soldfor']

    print(soldfor)

    g.db = connect_db()

    g.db.execute("UPDATE yardsale SET SF = ? WHERE ID = ?", (soldfor, ID,))

    g.db.commit()
    g.db.close()

    return redirect(url_for('index'))

你需要改变这个:

<form role="form" method="POST" action="{{ url_for('soldfor', ID={{ ID }}) }}">

对此:

<form role="form" method="POST" action="{{ url_for('soldfor', ID=ID) }}">

也来自文档:

When you define a route in Flask, you can specify parts of it that will be converted into Python variables and passed to the view function.

@app.route('/user/<username>')
def profile(username):
    pass

Whatever is in the part of the URL labeled will get passed to the view as the username argument. You can also specify a converter to filter the variable before it’s passed to the view.

@app.route('/user/id/<int:user_id>')
def profile(user_id):
    pass

您的错误是由需要参数的路由引起的,但您没有传入参数。您可能应该使用类似于上一个示例的方法来完成您想要做的事情。

有时也需要将默认值传递到视图函数中,以防您需要在不传递 ID 的情况下使用 URL。示例如下所示:

@app.route('/user/id/<int:user_id>')
def profile(user_id=0):
    pass