我想使用WTForms預填充選擇字段。 我想使用數據庫中的數據預先填充選擇字段(值和標籤)。預填充(查詢)SelectField - WTForms?
數據庫:
+----+----------+-------------------------------------+--------+
| id | category | description | status |
+----+----------+-------------------------------------+--------+
| 1 | Cinema | About movies | 1 |
| 2 | Play | About music. | 0 |
| 3 | News | Breaking news | 1 |
+----+----------+-------------------------------------+--------+
我想相當於QuerySelectField這樣:
class MyForm(Form):
category = SelectField(u'Category', choices=[('1', 'Cinema'), ('3','News')])
我到目前爲止已經做到了這一點:
def getCategories():
return Category.query.filter_by(status=1).all()
class MyForm(Form):
category = QuerySelectField(u'Category',
[validators.Required()],
query_factory = getCategories
)
標籤會以類似這個:
<select class="form-control" id="category" name="category">
<option value="1"><models.Category object at 0x105064910></option>
<option value="3"><models.Category object at 0x105064d50></option>
</select>