How to dynamically set default value in WTForms RadioField?
Asked Answered
T

2

15

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!

Tyrocidine answered 15/7, 2015 at 6:58 Comment(1)
You can pass default values in form constructor so you could 1st obtain the choices and then pass default choice to the MyForm constructor: MyForm(display='ONE')Phototypy
B
27

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.

Budget answered 15/1, 2016 at 21:25 Comment(0)
N
0

In line with the comment by Bartosz Grzybowski, you can pass defaults as a constructor:

class MyForm(Form):
    display = RadioField('display', default='ONE')

# Overwrite the default given in the field definition
myForm = MyForm(display='TWO')

This is because WTForms uses kwargs to provide field data

Newburg answered 6/11, 2023 at 10:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.