Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-wtf dynamic select field with an empty option

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.

like image 263
Holly Johnson Avatar asked Dec 01 '16 08:12

Holly Johnson


2 Answers

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

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

like image 186
fab Avatar answered Nov 15 '22 20:11

fab


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.

like image 39
ichbinblau Avatar answered Nov 15 '22 21:11

ichbinblau