我正在创建一个产品编辑表单,我需要预先填充以前的数据表单。
我正在做以下事情:
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的查询对象。
那么,有没有办法在运行时在selectfield上添加默认值?
答案 0 :(得分:18)
如果要设置默认值以使用表单呈现页面,可以创建自己的表单或设置值:
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
如果您想要根据请求设置默认表单数据:
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
答案 1 :(得分:10)
来自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