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.
You cound add the empty value also in the same line:
form.state.choices=[("", "---")]+[(s.id, s.name) for s in State.query.all()]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With