Flask / WTForms:动态 RadioField 的正确方法

Flask / WTForms: Right way to dynamic RadioField

我在使用 WTForms 创建动态 RadioField 时遇到问题...

当我尝试基本示例时:

targeting_type = RadioField('Label', choices=[('value', 'description'),
                                              ('value_two', 'whatever')])

一切正常。

当我尝试使用这个例子时:

表格中的值来自数据库。但是当我点击提交按钮时,页面“重新加载”但可能“没有数据”。

我的例子views.py:

form = TargetingTypeForm()
form.targeting_type.choices = [
    (targeting_type.id, targeting_type.name)
    for targeting_type in SettingsTargetingType.query.all()]

if form.validate_on_submit():
    print('test', form.targeting_type.data)

提交此表单后测试数据未打印:/

请问使用 WTForms + SQLAlchemy 查询创建 RadioField 的正确方法是什么?

感谢您的回答。

由于您使用 ID 作为值,我猜它是一个整数,因此您必须在 RadioField!

上使用 coerse 属性

试试这个:

form = TargetingTypeForm()
form.targeting_type.choices = [
    (targeting_type.id, targeting_type.name)
    for targeting_type in SettingsTargetingType.query.all()]
form.targeting_type.coerse = int
if form.validate_on_submit():
    print('test', form.targeting_type.data)

或将 coerse=int 添加到 TargetingTypeForm 中的 targeting_type 定义 class