Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
802 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...