如何在jinja模板中返回写入DB的SelectField(WTForms)中的选定选项



我有一个表单,有两个简单的输入(针对这个问题进行了简化(:第一个是用于选择颜色的下拉菜单,另一个是用于整数值的输入字段。该表单在一个页面中动态倍增(页面上有一个按钮用于添加另一个表单(,表单前缀具有独立的所有表单。

这是表单的代码:

class EnvelopeForm(FlaskForm):
line_color = SelectField('Line color', choices=['blue', 'black', 'green'], validators=[DataRequired()])
line_width = IntegerField('Line width', default=2, validators=[DataRequired()])
submit = SubmitField('calculate')

提交后,这些数据会像这样写入数据库:

class Envelope(db.Model):
id = db.Column(db.Integer, primary_key=True)
line_color = db.Column(db.String(20))
line_width = db.Column(db.Integer, default=2)
def __repr__(self):
return f"Envelope('{self.id}', '{self.line_color}', '{self.line_width}')"

在views.py中,我有一个额外的函数,可以从特定的表单输入中收集DB中的数据。我使用这个函数将DB中的值返回到jinja中特定表单的字段中。

这是函数:

def default_value(form_id):
return Envelope.query.filter_by(id=form_id).first()

这就是我使用该函数从DB返回值的方式:

{{ envelope_form.line_color.label }}
{{ envelope_form.line_color(class="", value=default_value(envelope_form.id).line_color) }}
{{ envelope_form.line_width.label }}
{{ envelope_form.line_width(class="", selected=default_value(envelope_form.id).line_width) }}

这只适用于IntegerField,但不适用于SelectField。如果我更改line_width的数字,无论页面刷新或向页面添加其他表单,它都会保持不变。当我从下拉菜单中更改一个表单的颜色时,它会在DB中更改,但在我将另一个表单添加到页面后不会返回到表单字段中。尽管在源信息中,它似乎是正确的选择值。不管我的颜色选择如何,在我添加另一种形式:后,它总是回到"蓝色">

在此处输入图像描述

所以我的问题是,为什么它对IntegerField有效,但对SelectField无效?

我知道这个答案有点晚了,但您的问题是EnvelopForm类。

choices参数是元组(名称、值(的列表,因此您的代码应该看起来像:

class EnvelopeForm(FlaskForm):
line_color = SelectField('Line color',
choices=[('blue', 'blue'), ('black', 'black'), ('green', 'green')],
validators=[DataRequired()]
)
line_width = IntegerField('Line width', default=2, validators=[DataRequired()])
submit = SubmitField('calculate')

您可以尝试使用sel.value和sel.data:

<code>sel = SelectField('label', choices=[('val', 'label'), ('val2', 'label2')])
print(sel.value, sel.data)
</code>
output:
<code>None None
</code>
Then after some changes:
<code>sel.value = 'val2'
sel.data = 'val'
print(sel.value, sel.data)
</code>
output:
<code>'val2' 'val'
</code>

但您需要在数据之前设置值。

最新更新