How to set default value dynamically in WTForms RadioField?
I am creating a website using Python Flask framework in which I am using WTForms . In one form, I got a RadioField like this:
display = RadioField('display', default='ONE')
This has no choice, because I do it later (which works great):
myForm = MyForm()
myForm.display.choices = [('ONE', 'one'), ('TWO', 'two')] # This works fine
Now I want to set the default for the RadioField after I have set the selection for it. So I tried to remove the default from the definition (I'm not sure if 'ONE'
it is always available) and I create the default after I created the options as I did above:
myForm.display.default = 'ONE'
Unfortunately, this has no effect. If I set it manually in the field definition as I do before it works fine, but not if I set it dynamically after I created the options.
Does anyone know how I can dynamically set a default RadioField in WTForms? All advice is appreciated!
source to share
You need to run myForm.process()
after adding selection and setting property default
:
myForm = MyForm()
myForm.display.choices = [('ONE', 'one'), ('TWO', 'two')]
myForm.display.default = 'ONE'
myForm.process() # process choices & default
This is because it default
extends to the value of a field (and in the case RadioField
, a property checked
) in a method process
that is called in the constructor.
source to share