Holly Johnson Holly Johnson - 8 days ago 4
Python Question

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.

Answer

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.