如何在不更改显示标签的情况下向WTForms Submit字段添加值



当我为字段设置值时,它会更改字段的显示标签。我使用的是FlaskWTForms,字段定义为:

class EditMultilpeChoiceQuestion(FlaskForm):
submit_update = SubmitField(name="submit_update", label="Update question")

在Jinja模板中,显示字段的代码为:

{{ form.submit_update(class="btn btn-primary btn-sm" value=question['database_id']) }}

在这个例子中,问题['database_id']的值是10,字段显示为:

添加值参数的按钮显示

如果我没有值=question['database_id'],该字段将显示为我想要的:

无数值参数的按钮显示

非常感谢任何建议。

用于呈现提交字段的小部件是SubmitInput,Github源代码,如下所示:

class SubmitInput(Input):
"""
Renders a submit button.
The field's label is used as the text of the submit button instead of the
data on the field.
"""
input_type = "submit"
def __call__(self, field, **kwargs):
kwargs.setdefault("value", field.label.text)
return super().__call__(field, **kwargs)

注意注释:

字段的标签用作提交按钮的文本,而不是字段上的数据。

请参阅下面的简单测试代码:

from wtforms.fields import SubmitField
from wtforms.form import Form

class F(Form):
a = SubmitField(label="Update question")

def test_submit_field():
# Pass no args
_html = F().a()
print(_html)
assert _html == """<input id="a" name="a" type="submit" value="Update question">"""
# assigning the value clears the label
_html = F().a(value=10)
print(_html)
assert _html == """<input id="a" name="a" type="submit" value="10">"""
# assign label and value
_html = F().a(label="Hello World", value=10)
print(_html)
assert _html == """<input id="a" label="Hello World" name="a" type="submit" value="10">"""

if __name__ == "__main__":
test_submit_field()

相关内容

最新更新