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?