Holly Johnson
Holly Johnson

Reputation: 509

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.

Upvotes: 12

Views: 10553

Answers (2)

fab
fab

Reputation: 1249

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

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

Upvotes: 15

ichbinblau
ichbinblau

Reputation: 4809

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.

Upvotes: 15

Related Questions