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!
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.