预填充(查询)SelectField - WTForms?
Pre-populate (Query) SelectField - WTForms?
我正在尝试使用 WTForms 预填充 Select 字段。
我想使用数据库中的数据预填充 Select 字段(值和标签)。
数据库:
+----+----------+-------------------------------------+--------+
| 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>
你做得很好。 QuerySelectField 使用模型对象的字符串表示形式进行显示。只需向您的类别模型添加一个 __str__
函数,returns 类别名称。
def __str__(self):
return self.name
我想你可以试试这个代码
categorie=QuerySelectField(query_factory=lambda:Category.query.filter_by(status=1).all(),get_label="name")
在你的表单中
你可以找到更多他们使用它的很棒的 turorial simpe crud app with forms
我正在尝试使用 WTForms 预填充 Select 字段。 我想使用数据库中的数据预填充 Select 字段(值和标签)。
数据库:
+----+----------+-------------------------------------+--------+
| 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>
你做得很好。 QuerySelectField 使用模型对象的字符串表示形式进行显示。只需向您的类别模型添加一个 __str__
函数,returns 类别名称。
def __str__(self):
return self.name
我想你可以试试这个代码
categorie=QuerySelectField(query_factory=lambda:Category.query.filter_by(status=1).all(),get_label="name")
在你的表单中 你可以找到更多他们使用它的很棒的 turorial simpe crud app with forms