在Flask中点击提交按钮时400 Bad Request

时间:2015-08-25 23:53:49

标签: python flask request submit

当我点击提交按钮时,我收到400 Bad Request错误。它实际上会重定向到'/'页面,但它会显示错误而不是页面。

这两个按钮位于同一页面上,但只有“添加”按钮有效。

<div class="col-lg-2 col-md-2">
    <form role="form" method="POST" action="/">
      <button type="submit" class="btn btn-success-register">Register</button>
    </form>
</div>

<div class="col-lg-2 col-md-2">
      <form action="/add">
        <button type="submit" class="btn btn-success-add">Add</button>
      </form><br class="visible-xs visible-sm">
</div>

根路线:

@app.route('/', methods=['GET', 'POST'])
def index():

    if request.method == "POST":
        if request.form['items'] == 'items':
            return redirect(url_for('data'))

    return render_template('register.html')

按钮所在的路线:

@app.route('/data', methods=['GET','POST'])
def data():

    deleted_items_list = []

    if request.method == "POST":
        if request.form['delete'] == 'delete':
            deleted_items = request.form.getlist('delete-check')
            for item in deleted_items:
                deleted_items_list.append(item.encode("utf-8"))
            for item in deleted_items_list:

                g.db = connect_db()

                g.db.execute('DELETE FROM yardsale WHERE Description = ?', (item,))

                g.db.commit()
                g.db.close()
                print("items were deleted")

    items = ["id"]
    g.db = connect_db()
    c = g.db.execute('select * from yardsale')
    items = [dict(id=row[0], description=row[1], seller=row[2], SP=row[3], MSP=row[4], SF=row[5], Notes=row[6]) for row in c.fetchall()]
    g.db.close()

    return render_template('data.html', items=items)

2 个答案:

答案 0 :(得分:0)

您正尝试访问request.form['items'],但未在表单中的任何位置定义。您最有可能使用此代码提出KeyError

要使此代码正常运行,您需要确保在表单中使用名称items

或者,如果您希望表单提交即使没有items输入也可以使用,您可以将代码更改为类似

    if request.form.get('items') == 'items':

如果未定义KeyError输入,则不会引发items

答案 1 :(得分:-1)

我认为你缺少名字属性。