如何在SelectMultipleFields之间传递数据?

时间:2019-03-30 21:07:25

标签: python flask wtforms

我是Flask和WTForms的新手,并且一直在为这个简单的任务而苦苦挣扎。我想显示一个选项列表。用户可以选择多个选项,然后这些选项将生成一个新的可选选项列表。

为简化操作,我只是尝试直接从一个SelectMultipleField中获取所选选项,并将其设置为第二个SelectMultipleField中的选项:

class SelForm(FlaskForm):
    choices = []
    selections = SelectMultipleField('Available Streams', choices=choices)
    submit = SubmitField('Choose Streams')
@streams_blueprint.route('/select', methods=['GET','POST'])
def select():
    # Grab a selectable list of studies from database.
    form = SelForm()
    db_objects = [(stream.id, stream.name) for stream in Stream.objects()]
    form.selections.choices = db_objects
    if form.validate_on_submit():
        form2 = SelForm()
        selections = form.selections.data
        form2.selections.choices = selections
    else:
        form2 = SelForm()
    return render_template('select_streams.html', form=form, form2=form2)

无论我尝试什么,表单都始终以其初始状态(form.selections.choices=db_objectsform2.selections.choices=[])呈现。 validate_on_submit段不执行任何操作。单击提交后如何获取Form2的更新?

1 个答案:

答案 0 :(得分:0)

在整个周末中,我的头都撞了一下,我终于找到了答案。问题是SelectMultipleField中的默认验证器实际上不起作用。如果我将validate_on_submit替换为is_submitted,则代码将运行。这个版本可以满足我的要求:

@streams_blueprint.route('/select', methods=['GET','POST'])
def select():
    # Grab a selectable list of studies from database.
    form = SelForm()
    db_objects = [(stream.id, stream.name) for stream in Stream.objects()]
    form.selections.choices = db_objects
    if form.is_submitted():
        form2 = SelForm()
        selections = form.selections.data
        new_objects = [(stream.id, stream.name) for stream in Stream.objects(id__in=selections)]
        form2.selections.choices = new_objects
    else:
        form2 = SelForm()
    return render_template('select_streams.html', form=form, form2=form2)

如果需要验证器,则必须为此字段类型编写自定义验证器。

Works as intended