Flask-wtf dynamic select field with an empty option
Asked Answered
B

2

12

I want to populate a select field based a query search.

But I also want an empty option.

This is my current code

 form.state.choices=[(s.id, s.name) for s in State.query.all()]

the result is

  <select>
  <option value="CA">California</option>
  <option value="FL">Florida</option>
  </select>

the desired result is

<select>
<option value=""></option>
<option value="CA">California</option>
<option value="FL">Florida</option>
</select>

It would be cool if is also not valid if the select option is empty.

Brewing answered 1/12, 2016 at 8:13 Comment(0)
O
15

You may want to add the empty value like this:

choices = [("", "---")]
form.state.choices=[choices.append((s.id, s.name)) for s in State.query.all()]

Then you can check whether the value is empty string to validate the field.

Obstruent answered 1/12, 2016 at 9:44 Comment(4)
is there a way to specify a different font for the first tuple? Specifically, the color so that it might be 'greyed out'?Stiles
It's not working in Python 3.7.3. But work when I use @fab answer.Resuscitate
[mylist.append(x) for x in some_sequence] will return a list of Nones.Amaris
I don't know why this is the accepted answer; it's just plain wrong. As @Amaris says, this results in a list of None. Answer from @fab below should be accepted.Sulphathiazole
P
15

You cound add the empty value also in the same line:

form.state.choices=[("", "---")]+[(s.id, s.name) for s in State.query.all()]

Precontract answered 12/5, 2018 at 13:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.