kramer65
kramer65

Reputation: 53873

How to dynamically set default value in WTForms RadioField?

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!

Upvotes: 15

Views: 6524

Answers (2)

CaptainRuhrpott
CaptainRuhrpott

Reputation: 70

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

Upvotes: 0

jeinarsson
jeinarsson

Reputation: 410

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.

Upvotes: 27

Related Questions