Flask-wtf:使用 kwarg 设置字段的初始值

Flask-wtf: Using a kwarg to set the initial value for a field

我想使用 kwarg 来设置表单字段的初始值。我以前做过类似的事情:

from wtforms import Form
from wtforms.fields import StringField

class BasicForm(Form):
    inputField = StringField("Name")

basic_form_kwargs = {"inputField" : "Example"}
basic_form = BasicForm(**basic_form_kwargs)
print basic_form.inputField
#<input id="inputField" name="inputField" type="text" value="Example">

这段代码如我所料。 value 属性设置为 "Example"。然而,当我开始使用 FormFields 时,它并没有像我预期的那样工作。

from wtforms import Form
from wtforms.fields import StringField

class ChildForm(Form):
    inputField = StringField("Name")
class ParentForm(Form):
    childWrapper = FormField(ChildForm)

complex_form_kwargs = {"childWrapper-inputField" : "Example"}
complex_form = ParentForm(**complex_form_kwargs)
print complex_form.childWrapper.inputField
#<input id="childWrapper-inputField" name="childWrapper-inputField" type="text" value="">

需要传递什么 kwarg 才能在使用 FormFields 时设置 inputField 的值?

就像您将字典传递给父级表单一样,您需要像这样将字典传递给子表单:

kwargs = {"childWrapper": {"inputFIeld": "Example2"}}
form = ParentForm(**kwargs)