How do you set a default value for a WTForms SelectField?

后端 未结 7 637
-上瘾入骨i
-上瘾入骨i 2020-11-29 04:09

When attempting to set the default value of a SelectField with WTForms, I pass in value to the \'default\' parameter like so.

class TestForm(Form):
  test_fi         


        
7条回答
  •  生来不讨喜
    2020-11-29 04:52

    I believe this problem is caused by the Field's data attribute overriding the default with something that WTForms doesn't understand (e.g. a DB model object -- it expects an int). This would happen if you have populated your form in the constructor like so:

    form = PostForm(obj=post)
    

    the solution is to manually set the data attribute after the form has been populated:

    form = PostForm(obj=post)
    form.category.data = (post.category.id
                          if page.category
                          else 0) # I make 0 my default
    

提交回复
热议问题