使用Python Flask的复选框从HTML表单获取信息

时间:2015-12-03 17:31:48

标签: python html forms flask

我尝试动态创建带有复选框的网络表单,并使用用户选择填充列表。例如,如果用户要从表单中选择test1和test2,我希望在[' test1',' test2']的python中有一个列表。

我正在使用带有Jinja2和Python的Flask。但是,当我提交表单时,我会收到400条消息(错误请求)。

以下是相关的Python代码。

from flask import Flask, render_template, request, redirect

CASES = ['test1', 'test2', 'test3', 'test4']

@app.route("/")
def template_test():
return render_template('template.html', title="Home")

@app.route("/TestCases")
def TestCases():
    return render_template('testcases.html', cases=CASES, title="Test Cases")

@app.route("/info", methods=['POST'])
def getinfo():
    if request.method == 'POST':
        test = request.form['checks']
        print test
        return redirect('/')
    else:
        return redirect('/')

以下是模板中的相关html代码(testcases.html)。

<form action="info" method="post" name="checks">
  {% for c in cases %}
  <input type="checkbox" name={{c}} value='checks'> {{c}}<br>
  {% endfor %}
  <br>
  <input type="submit" value="Submit">

我不是python的新手,但这是我第一次尝试使用Flask和Jinja2。

1 个答案:

答案 0 :(得分:1)

提交的表单数据中没有checks,因为没有名为<input>的{​​{1}}元素。要查看打印的复选框,请尝试:

"checks"

print request.form.keys()

调试表单子的一种方法是使用httpbin.org提供的服务,如下所示:

for k,v in request.form.items():
    print k, v

当我选择几个复选框时,我得到以下结果。请注意,每个<form action="http://httpbin.org/post" method="post" name="checks"> 元素都会生成<input>的独特成员。

form

一种可能的解决方案是修改模板和应用。

模板:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "test1": "checks", 
    "test3": "checks"
  }, 
  "headers": {
    ... # Deleted for brevity
}

应用程式:

<input type="checkbox" value="{{c}}" name="checks"> {{c}}<br>
相关问题