您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 使用带有SelectMultipleField的WTForms的Flask应用程序

5b51 2022/1/14 8:22:07 python 字数 3528 阅读 548 来源 www.jb51.cc/python

我有一个Flask应用程序,它使用WTForms进行用户输入.它在表单中使用SelectMultipleField.我似乎无法让应用程序在选中时在字段中发布所有项目;它只发送选择的第一个项目,无论用户选择了多少. Flask documentation说明了这个字段类型发送的数据,但我没有看到这种行为: The data on the SelectMultipleField is stored a

概述

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应用程序所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶