I am attempting to create a dynamic drop down (SelectField) with WTForms. I have read the documentation and have looked at quite a few answers on stack, and all of the examples involve iterating over a db query.
I simply want to iterate over a list (that's generated from an external API call) to inject the SelectField choices. For example:
class ToolForm(FlaskForm):
myField3 = SelectField(u'Select Account', choices=[], coerce=int)
@app.route("/test", methods=['GET', 'POST'])
def test():
form = ToolForm()
accounts5 = []
if request.method == 'POST':
if request.form['submit_button'] == 'Select Account':
#code that generates list called "accounts5"
acctchoices = [(c.id,c.name) for c in accounts5]
form.myField3.choices = acctchoices
return render_template('test.html', title='test', form=form, accounts5=accounts5)
And my relevant HTML looks like:
<div class="form-group">
{{ form.myField3.label(class="form-control-label") }} {% if form.myField3.errors %} {{
form.myField3(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for errors in form.myField3.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %} {{ form.myField3(class="form-control form-control-lg") }} {% endif %}
</div>
<form action="http://127.0.0.1:5000/test" method="post">
<input type="submit" class="btn btn-outline-info" name="submit_button" value="Select Account">
</form>
When I click "Select Account" I get an 'int' object has no attribute 'id' error. I thought this might be a data type issue so I tried with a list of strings but to no avail.
My question is, how can I populate my SelectField from a list?
accounts5 = [("test", '1'), ("tested", '3'), ("testing", '3')]but got'tuple' object has no attribute 'id'accounts5 = [('1', 'test'), ('3','tested'),('4','testing')]andform.myField3.choices = accounts5then it will work. The list you're showing doesn't have an 'id' or 'name' attribute for a primary key (the database object you've taken the example from does though).