【问题标题】:Getting information from HTML Form with checkboxes with Python Flask使用 Python Flask 从带有复选框的 HTML 表单中获取信息
【发布时间】:2015-12-04 02:09:06
【问题描述】:

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

我正在使用带有 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('/')

这是来自模板 (testcases.html) 的相关 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。

【问题讨论】:

  • 你在表单定义中尝试过 action="/info" 吗?
  • 是的,试过了。同样的问题。

标签: python html forms flask


【解决方案1】:

提交的表单数据中没有checks,因为没有名为"checks"&lt;input&gt;元素。要查看打印了哪些复选框,请尝试:

print request.form.keys()

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

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

<form action="http://httpbin.org/post" method="post" name="checks">

当我选择几个复选框时,我得到以下结果。请注意,每个 &lt;input&gt; 元素都会产生 form 的不同成员。

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

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

模板:

<input type="checkbox" value="{{c}}" name="checks"> {{c}}<br>

应用程序:

    test = request.form.getlist('checks')

【讨论】:

  • 这很有效,或者至少让我比以前更进一步。然而,它不返回字典,它似乎返回一个列表。谢谢。不确定这是不是最好的方法,但至少它让我暂时克服了这个问题。
  • request.form.getlist() 按照您的要求返回一个列表,“我希望在 python 中有一个 ['test1', 'test2'] 的列表。
猜你喜欢
  • 2017-11-19
  • 2016-09-20
  • 1970-01-01
  • 2014-08-13
  • 2021-07-15
  • 2011-11-22
  • 1970-01-01
  • 2020-05-15
  • 1970-01-01
相关资源
最近更新 更多