我有一个Flask应用程序,它使用WTForms进行用户输入.它在表单中使用SelectMultipleField.我似乎无法让应用程序在选中时在字段中发布所有项目;它只发送选择的第一个项目,无论用户选择了多少.
Flask documentation说明了这个字段类型发送的数据,但我没有看到这种行为:
The data on the SelectMultipleField is stored as a list of objects,
each of which is checked and coerced from the form input.
这是一个完整的,最小的Flask应用程序,说明了这一点:
#!/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 %} <h1>Set Language</h1> <form method="POST" action="/"> <div>{{ form.language.label }} {{ form.language(rows=3,multiple=True) }}</div> <button type="submit" class="btn">Submit</button> </form> {% endblock %} """ completed_template = """ {% block content %} <h1>Language Selected</h1> <div>{{ language }}</div> {% 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将request.form作为werkzeug MultiDict对象返回.这有点像字典,只是为了不警觉的陷阱.
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.
但是,我认为有一种更简单的方法.
你可以帮我一个忙吗?
language = request.form['language']
同
language = form.language.data
并看看是否有任何不同? WTForms应该处理MultiDict对象,并且只是为您自己返回一个列表,因为您已经将表单数据绑定到它.