Flask WTForms validate_on_submit无法正常工作

问题描述 投票:0回答:1

我是Web开发的新手,正在使用Flask创建一个房地产价格预测网站。

我有一个功能validate_on_submit无法正常工作。它不显示任何错误,表单已提交,只是不验证。单击提交表单后,需要转到下一页。这是代码:

@app.route('/route1', methods=['POST', 'GET'])
def predict():
    form = Form_1()

    # These errors, submitted and validated just for some context, not in the actual code

    print(form.errors) # Returns {}

    if form.submit():
       print("submitted") # Returns "submitted"

    if form.validate():
       print("validated") # Page shows error 'NoneType' object is not iterable

    # more code

    if form.validate_on_submit():
        print("validated on submit") # This is not working

        # more code

        return redirect(url_for('page_x'))
    return render_template('page_x.html', title='Page X', form=form)

这里是HTML:

<div class="content" align="center">
    <div class="content-section">
        <form method = "POST" action="">
            {{ form.hidden_tag() }}
            <table style="width:15%">
                <tr>
                    <td>{{ form.select_field.label() }}</td>
                    <td>:</td>
                    <td>{{ form.select_field() }}</td>
                </tr>
                <tr>
                    <td></td>
                    <td></td>
                    <td>{{ form.submit() }}</td>
                </tr>
            </table>
        </form>
    </div>
</div>

这很奇怪,因为我有另一个与此工作类似的代码:

@app.route('/route2', methods=['POST', 'GET'])
def add_data():
    form = Form_2()
    if form.validate_on_submit():

        # more code

        return redirect(url_for('page_y')
    return render_template('page_y.html', title='Page Y', form=form)

HTML:

<div class="content" align="center">
    <h1>Help Us Improve by Uploading a New Dataset</h1>
    <div class="content-section">
        <form method="POST" action="" enctype="multipart/form-data">
            {{ form.hidden_tag() }}
            {{ form.add_file() }} {{ form.submit() }}
        </form>
    </div>
</div>

我不确定出了什么问题。任何帮助,将不胜感激。谢谢。

python web flask flask-wtforms wtforms
1个回答
0
投票

我发现了问题。我使用的是SelectField表单。我放置了coerce参数,它可以工作。

帮助我的文章:Not a Valid Choice for Dynamic Select Field WTFORMS

© www.soinside.com 2019 - 2024. All rights reserved.