关于python:Flask应用程序将WTForms与SelectMultipleField一起使用

Flask App Using WTForms with SelectMultipleField

我有一个Flask应用程序,该应用程序使用WTForms作为用户输入。 它使用SelectMultipleField形式。 选择后,我似乎无法让该应用发布该字段中的所有项目; 它只会发送选择的第一个项目,而不管用户选择了多少个项目。

Flask文档说明了有关从此字段类型发送的数据的信息,但我没有看到这种现象:

The data on the SelectMultipleField is stored as a list of objects,
each of which is checked and coerced from the form input.

这是一个完整的,最小的Flask应用程序,它说明了这一点:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env python

from flask import Flask, render_template_string, request
from wtforms import Form, SelectMultipleField

application = app = Flask('wsgi')

class LanguageForm(Form):
    language = SelectMultipleField(u'Programming Language', choices=[('cpp', 'C++'), ('py', 'Python'), ('text', 'Plain Text')])

template_form ="""
{% block content %}
Set Language

<form method="POST" action="/">
    {{ form.language.label }} {{ form.language(rows=3, multiple=True) }}
    <button type="submit" class="btn">Submit</button>    
</form>
{% endblock %}

"""


completed_template ="""
{% block content %}
Language Selected

{{ language }}

{% endblock %}

"""


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

    if request.method == 'POST' and form.validate():
        print"POST request and form is valid"
        language =  request.form['language']
        print"languages in wsgi.py: %s" % request.form['language']
        return render_template_string(completed_template, language=language)

    else:

        return render_template_string(template_form, form=form)

if __name__ == '__main__':
    app.run(debug=True)

Flask作为werkzeug MultiDict对象返回request.form。 这有点像一本字典,只为那些粗心的人设陷阱。

http://flask.pocoo.org/docs/api/#flask.request
http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict

MultiDict implements all standard dictionary methods. Internally, it saves all values for a key as a list, but the standard dict access methods will only return the first value for a key. If you want to gain access to the other values, too, you have to use the list methods.

但是,我认为有一种更简单的方法。
您能帮我一个忙,然后尝试更换:

1
language =  request.form['language']

1
language =  form.language.data

看看有什么不同吗? WTForms应该处理MultiDict对象,并因为将表单数据绑定到该对象而只为您返回一个列表。