如何在WTForms RadioField中动态设置默认值? [英] How to dynamically set default value in WTForms RadioField?

查看:1763
本文介绍了如何在WTForms RadioField中动态设置默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python Flask 框架构建一个网站,我在其中使用 WTForms 。在一种形式中,我有一个 RadioField a>定义如下:

$ p $ display = RadioField('display',default ='ONE')
code>

这没有定义任何选择,因为我这样做lateron(它工作得很好):

  myForm = MyForm()
myForm.display.choices = [('ONE','one'),('TWO','two ')]#This work fine

我现在要为RadioField 设置默认值,之后我设置了它的选择。所以我试着从定义中删除默认值(我不知道是否'ONE'总是可用的选择),并创建了默认值像上面这样:

  myForm.display.default ='ONE'

不幸的是,这根本没有任何效果。如果我在字段定义中手动设置它,就像我以前做的那样,但是如果我在创建选项之后动态地设置它,那么不是这样。

有人知道我可以在WTForms中动态设置RadioField的默认值?所有的提示都是值得欢迎的!

您需要运行 myForm.process()默认属性:

  myForm = MyForm()
myForm.display.choices = [('ONE','one'),('TWO','two')]
myForm.display.default ='ONE'
myForm.process()#进程选择&默认

这是因为默认被传播( RadioField 已检查属性)的字段值( process 方法,它在构造函数中调用。


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.

这篇关于如何在WTForms RadioField中动态设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆