WtfFroms 预填充 ListField

WtfFroms Pre poulate ListField

我想在渲染模板之前将数据填充到列表字段。 这是我目前所拥有的。

class SizeVariationForm(Form):
    name = TextField("name")
    sku = TextField("SKU Number")


class AddVariationForm(NewListingForm):
    item_list = FieldList(FormField(SizeVariationForm))
    add_field = SubmitField('Add Variations')


@app.route('/index', methods=['GET', 'POST'])
def add_inputs():
    form = AddVariationForm(request.form)
    if form.add_field.data:
        # what i want is to poluate sku data here

        new_variation = form.item_list.append_entry()
        return render_template('index')

当前结果为

<input id="item_list-0-variation"  value="">

想要的结果是

<input id="item_list-0-variation" value="Some Value here">

您会得到预期的输出,但我不确定这是您想要的。

class SizeVariationForm(Form):
    name = TextField("Name")
    sku = TextField("SKU")

class TestForm(Form):
    item_list = FieldList(FormField(SizeVariationForm))
    add_field = SubmitField("Add Variations")

@app.route('/index', methods=['GET', 'POST'])
def add_inputs():
    f = SizeVariationForm()
    form = AddVariationForm()
    if request.method == 'POST':
        f.name.data = "Same value"
        f.sku.data = "sku data"
        form.item_list.append_entry(f)
    return render_template('index.html', form=form)

#index.html
<form method="POST", action="/">
        {{form.item_list}}
        {{form.add_field.label}}{{form.add_field}}
</form>

基础 class Field 接受一个 default 参数。

default – The default value to assign to the field, if no form or object input is provided. May be a callable.

将此参数提供给字段的初始化方法。即

class MyForm(Form):
    foo = SomeField("Bar", default="Example")

http://wtforms.simplecodes.com/docs/0.6.1/fields.html