【问题标题】:How can I pass data between SelectMultipleFields?如何在选择多个字段之间传递数据?
【发布时间】:2019-03-30 21:07:24
【问题描述】:

我是 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更新?

【问题讨论】:

    标签: python flask wtforms


    【解决方案1】:

    在整个周末都在努力解决这个问题之后,我终于找到了答案。问题是SelectMultipleField 中的默认验证器实际上不起作用。如果我用is_submitted 替换validate_on_submit,代码就会运行。这个版本做了我想要的:

    @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)
    

    如果我需要验证器,我将不得不为此字段类型编写自定义验证器。

    【讨论】:

      猜你喜欢
      • 2011-07-08
      • 2020-06-04
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      相关资源
      最近更新 更多