如何在选定的多个字段之间传递数据?

2024-04-26 23:11:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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?你知道吗


Tags: form列表dbstreamobjects选项selectstreams
1条回答
网友
1楼 · 发布于 2024-04-26 23:11:52

整个周末我都在绞尽脑汁,终于找到了答案。问题是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)

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

Works as intended

相关问题 更多 >