在提交时验证表单不起作用

2024-04-18 19:26:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我是网络开发新手,我正在使用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>

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


Tags: divformreturnifonpagecodecontent