19

我正在创建一个产品编辑表单,我需要在表单中预先填充以前的数据。

我正在执行以下操作:

Product(form):
    product = TextField('name')
    category = SelectField('category', choice=[(1,'one'),(2,'two')])

在视图中:

form.product.data = 'A product name from the database'
form.category.data = 'a category name' #This does not work

问题出在 SelectField 上。

我知道我可以在 SelectField 上设置一个“默认”值。但是,这发生在表单定义类中,我还没有来自 sqlalchemy 的查询对象。

那么,有没有办法在运行时在选择字段上附加默认值?

4

2 回答 2

18

If you want set default value to render page with form you can create own form or set value:

class Product(Form):
    product = TextField('name')
    category = SelectField('category', choices=[(1,'one'),(2,'two')])

# create instance with predefined value:
form1 = Product(category=2)
# form1.product == <input id="product" name="product" type="text" value="">
# form1.category == <select id="category" name="category">
#                     <option value="1">one</option>
#                     <option selected value="2">two</option>
#                   </select>
# from1.product.data == None
# form1.category.data == 2

# create own form if it need many times:
Product2 = type('Product2', (Product,), {
    'category': SelectField('category', default=2, choices=[(1,'one'),(2,'two')])
})
form2 = Product2()
# form2.product == <input id="product" name="product" type="text" value="">
# form2.category == <select id="category" name="category">
#                     <option value="1">one</option>
#                     <option selected value="2">two</option>
#                   </select>
# from2.product.data == None
# form2.category.data == 2

If you want set default form data on request:

with app.test_request_context(method='POST'):
    form = Product(request.form)
    # form5.category.data == None

    form = Product(request.form, category=2)
    # form5.category.data == 2

with app.test_request_context(method='POST', data={'category': 1}):
    form = Product(request.form)
    # form5.category.data == 1

    form = Product(request.form, category=2)
    # form5.category.data == 1
于 2013-07-14T09:09:18.933 回答
12

来自 WTForms 文档

请注意,choices 关键字只计算一次,因此如果您想创建一个动态下拉列表,您需要在实例化后将选择列表分配给该字段。

Product(form):
    product = TextField('name')
    category = SelectField('category')

然后在你看来说

form.category.choices = [list of choices with chosen data]

更多细节在这里找到: http ://wtforms.simplecodes.com/docs/0.6.1/fields.html#wtforms.fields.SelectField

于 2013-07-13T18:54:18.067 回答