Search code examples
pythonwebflaskflask-wtformswtforms

Flask WTForms validate_on_submit not working


I am new in Web Development and I am using Flask to create a property price prediction website.

I have a function validate_on_submit that is not working. It does not show any error, the form is submitted, it just does not validate. When the submit form is clicked, it needs to go to the next page. Here is the code:

@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)

Here is the 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>

It is weird because I have another code similar to this that worked:

@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>

I am not sure what went wrong. Any help would be appreciated. Thank you.


Solution

  • I found the problem. It is with the SelectField form that I use. I place a coerce arguments and it works.

    Article that helped me: Not a Valid Choice for Dynamic Select Field WTFORMS