【问题标题】:wtforms SelectField always returns None [duplicate]wtforms SelectField 总是返回 None [重复]
【发布时间】:2020-06-14 03:03:04
【问题描述】:

所以,我正在使用 FlaskForm 和 wtforms 构建一个包含 SelectField 的 Web 表单。当用户提交表单时,我可以毫无问题地读取 StringFields,但是 SelectField 的值始终为 None。

我已经找了几个小时来解决这个问题,但既没有找到答案也没有解释我的代码出了什么问题。

我查看了以下线程但没有成功:

还有更多,我再也找不到了。我还阅读了documentationthese 示例。

这里是一些重现问题的代码:

from flask import Flask, url_for, redirect, request, render_template_string
from flask_wtf import FlaskForm
from wtforms import SelectField, SubmitField

app = Flask(__name__)
app.config["SECRET_KEY"] = "very_secret"

# basic html template
my_html = """
<div class="content-section">
        <form method="POST" action=".">
            {{form.hidden_tag()}}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">New Task</legend>


                <div class="form-group">
                    {{ form.select.label(class="form-control-label")}}
                    <select class="form-control" id="continent_selector">
                        {% for choice in form.select.choices %}
                            <option value="{{ choice[1] }}">{{ choice[0] }}</option>
                        {% endfor %}
                      </select>
                </div>


            </fieldset>
            <div class="form-group">
                {{ form.submit(class="btn btn-outline-info")}}
            </div>
        </form>
    </div>
"""


class TaskForm(FlaskForm):
    tuple_list = [("Choice_0", 0), ("Choice_1", 1)]
    select = SelectField("select", choices=tuple_list)
    submit = SubmitField("Create Task")


@app.route("/", methods=["GET", "POST"])
def new_task():
    form = TaskForm()
    if request.method == "POST": 
        print("-------------FORM--------------")
        print(form.data)
        print("-------------END--------------")
        return str(form.select.data)
    return render_template_string(my_html, title="New Task", form=form)


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

打印出form.data如下:

{'select': 'None', 'submit': True, 'csrf_token': 'some_hash'}

如果有人能指出我做错了什么,那就太好了:)

【问题讨论】:

    标签: python flask flask-wtforms wtforms


    【解决方案1】:

    您的select 标签需要一个名称。替换:

    <select class="form-control" id="continent_selector">
    

    与:

    <select class="form-control" id="continent_selector" name="select">
    

    【讨论】:

    • 给这位学者点赞!
    猜你喜欢
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    相关资源
    最近更新 更多