1

I have the following file (app.py) that generates a Flask instance and defines a few routes and declares/initiates a simple form:

from flask import Flask, render_template, url_for
from flask_wtf import FlaskForm
import wtforms as wtf
from wtforms.fields.html5 import DecimalRangeField

app = Flask(__name__)
app.config['SECRET_KEY'] = 'youll-never-guess'

class Form(FlaskForm):
    age = DecimalRangeField('age', default=30)
    submit = wtf.SubmitField('submit')

@app.route('/form/', methods=['GET'])
def form():
    form = Form()
    return render_template('form.html', form=form)

@app.route('/form/submit/', methods=['POST'])
def submit_form():
    return 'form submitted!'

def main():
    app.run(debug=True, port=5000)

if __name__ == '__main__':
    main()

where the templates/form.html file is as follows:

<form id="form" action="{{ url_for('submit_form') }}" method="POST" onchange="submitForm(this);">
  {% for field in form %}
    {{ field }}
  {% endfor %}
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script>
  function submitForm(form) {
    console.log(`submitting form ${form} ... `);
    $(form).submit();
  }
</script>

When I change the slider the console prints submitting form [object HTMLFormElement] ... but does not seem to call the view function submit_form. However, when I click the submit button the /form/submit/ URL is rendered with the text form submitted!. Why is this, please?

stasiekz
  • 1,775
  • 5
  • 22
ajrlewis
  • 2,968
  • 3
  • 33
  • 67

2 Answers2

1

You have to rename submit field on the form because submit method/handler is shadowed by the name/id attribute.

class Form(FlaskForm):
    age = DecimalRangeField('age', default=30)
    sub = wtf.SubmitField('sub')

Alternatively you can add your form button directly in the template but it can't have id nor name submit.

stasiekz
  • 1,775
  • 5
  • 22
0

In your code, the change method has a call back function and inside this call back function, this refers to the current call back function scope, which doesn't have any submit method.

Therefore, fetch the form object using JQuery or vanilla JS as follows:

var form = document.getElementById("form");
$(form).submit();
ajrlewis
  • 2,968
  • 3
  • 33
  • 67
vipul patel
  • 668
  • 4
  • 7
  • thanks -- I've made these changes but the `$(form).submit()` method is still not calling the view function ... – ajrlewis Sep 25 '19 at 13:43