How to dynamically set default value in WTForms RadioField?

江枫思渺然 提交于 2019-11-29 13:49:45

问题


I'm building a website with the Python Flask framework in which I use WTForms. In one form I've got a RadioField defined as follows:

display = RadioField('display', default='ONE')

This does not have any choices defined, because I do that lateron (which works perfectly fine):

myForm = MyForm()
myForm.display.choices = [('ONE', 'one'), ('TWO', 'two')]  # This works fine

I now want to set the default value for the RadioField after I set the choices for it. So I tried removing the default value from the definition (I'm not sure if 'ONE' is always an available choice) and I create the default value after I create the choices like I do above:

myForm.display.default = 'ONE'

Unfortunately this has no effect at all. If I set it manually in the Field definition like I do before it works fine, but not if I set it dynamically after I created the choices.

Does anybody know how I can dynamically set the default value for a RadioField in WTForms? All tips are welcome!


回答1:


You need to run myForm.process() after adding the choices and setting the default property:

myForm = MyForm()
myForm.display.choices = [('ONE', 'one'), ('TWO', 'two')]
myForm.display.default = 'ONE'
myForm.process() # process choices & default

This is because the default is propagated to the field value (and, in the case of RadioField, the checked property) in the process method, which is called in the constructor.



来源:https://stackoverflow.com/questions/31423495/how-to-dynamically-set-default-value-in-wtforms-radiofield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!