Flask - WTForm - 使用查询结果作为RadioField选择

时间:2016-03-18 12:52:10

标签: python flask wtforms

参考以下表格。

CONTROL_CHOICES = Session.query(schema.OfficeType).order_by(schema.OfficeType.descr).all()
CONTROL_CHOICES = [(office.id, office.descr) for office in CONTROL_CHOICES]

class ControlForm(Form):

    institution = RadioField('Institution', choices=CONTROL_CHOICES)

    date = DateField('Date')
    submit = SubmitField('SUBMIT')

简单HTML

<form action="composition_profile" method="get">
        {{control_form.hidden_tag()}}
        {{control_form.institution.label}}
        {{control_form.institution}}
        {{control_form.date.label}}
        {{control_form.date}}
        {{control_form.submit}}

    </form>

无线电字段已成功打印。enter image description here

但是,在填写表单时,validate_on_submit()不会打印错误,但不会在if

中执行代码

validate()会输出以下错误。

  

{'机构':['不是一个有效的选择']}

@app.route('/composition_profile', methods=['GET', 'POST'])
def composition_profiles():
    if request.method == 'GET':
        if request.args.get('institution') and request.args.get('date'):
            form = ControlForm(request.args)
            print(form.institution.data)

            if form.validate():

                print('terms')
            print(form.errors)

知道它是如何导致选择不当的吗?我不确定发生了什么。将其更改为QuerySelectField有效,但我想要无线电功能

2 个答案:

答案 0 :(得分:1)

考虑重新分解:

def my_view():
    class F(MyBaseForm):
        pass

    F.username = TextField('username')
    for name in iterate_some_model_dynamically():
        setattr(F, name, TextField(name.title()))

    form = F(request.POST, ...)
    # do view stuff

来源:http://wtforms.simplecodes.com/docs/1.0.1/specific_problems.html#dynamic-form-composition

答案 1 :(得分:0)

问题似乎是由于WTForm期望Value字段为String而不是Integer

而导致的

更改

CONTROL_CHOICES = [(office.id, office.descr) for office in CONTROL_CHOICES]

CONTROL_CHOICES = [(str(office.id), office.descr) for office in CONTROL_CHOICES]

缓解问题