概述
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)
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对象,并且只是为您自己返回一个列表,因为您已经将表单数据绑定到它.
总结
以上是编程之家为你收集整理的python – 使用带有SelectMultipleField的WTForms的Flask应用程序全部内容,希望文章能够帮你解决python – 使用带有SelectMultipleField的WTForms的Flask应用程序所遇到的程序开发问题。
如果您也喜欢它,动动您的小指点个赞吧