【问题标题】:Flask / WTForms: Right way to dynamic RadioFieldFlask / WTForms:动态 RadioField 的正确方法
【发布时间】:2018-09-06 08:18:03
【问题描述】:

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

当我尝试基本示例时:

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

一切正常。

当我尝试使用此示例时: Flask-SQLAlchemy wtform based on db

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

我的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 的正确方法是什么?

感谢您的任何回答。

【问题讨论】:

  • 试试form.tergeting_type.coerse = int

标签: python-3.x flask sqlalchemy flask-wtforms


【解决方案1】:

由于您使用 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 定义

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 2020-01-18
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    相关资源
    最近更新 更多