Setting a default value in the selectfield, using wtforms and flask

kfk picture kfk · Jul 13, 2013 · Viewed 24.6k times · Source

I am creating a product edit form and I need the form to be pre-populated with the previous data.

I am doing the following:

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

In the view:

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

The issue is with the SelectField.

I understand there is a 'default' value I can set on SelectField. However, this happens in the form definition class and there I do not have the query object from sqlalchemy yet.

So, is there a way to append a default on selectfield on run time?

Answer

tbicr picture tbicr · Jul 14, 2013

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