New to this, trying to build an app following a well known Flask tutorial, using Flask-bootstrap, Flask-wtforms, Jinja etc
I have a form with 2 select fields and a button.
class Form(FlaskForm):
school_year = SelectField('School year', choices=some_tuples_list)
category = SelectField('Category', choices=[])
submit = SubmitField('submit')
I want only the first field to be pre-populated, and the other to get populated (on the client side?) based on the previous field's selected value.
In the template I try something like
{{ form.school_year(**{"onchange":"getCategories()"}) }}
which works ok (provided that I return the tuples list to populate the next field, using the proper javascript and route) but I want something like the following
{{ wtf.form_field(form.school_year(**{"onchange":"getCategories()"})) }}
which doesn't work (Error: wtforms.widgets.core.HTMLString object' has no attribute 'flags')
So, I guess my question really is: how do I implement an onChange event on this wtf form field? (And is this what I have to do, or is there a way from the view function?)
Thanks in advance.
Here is an example implementation of this logic to work with WTForms native functionality. The trick here, is if you want to use WTForms validation, you need to instantiate the form with every possible value, then modify the available options in Javascript to show the filtered values based on the other select.
For this example I'm going to use the concept of States and Counties (I work with a lot of geo data so this is a common implementation I build).
Here's my form, I've assigned unique IDs to the important elements to access them from Javascript:
Now, the Flask view to instantiate and process the form:
A Flask view to respond to XHR requests for Counties:
And, finally, the Javascript to place at the bottom of your Jinja template. I'm assuming because you mentioned Bootstrap, that you are using jQuery. I'm also assuming this is in line javascript so I'm using Jinja to return the correct URL for the endpoint.