Flask WTF表单:如果用户在SelectMultipleField中选择特定选项,是否可以显示新字段?

Flask WTF表单:如果用户在SelectMultipleField中选择特定选项,是否可以显示新字段?,flask,flask-wtforms,Flask,Flask Wtforms,我刚开始使用Flask WTF表单。我可以和他们一起做我需要的一切,除了我似乎不知道一件事。我有一个多选字段,向用户显示各种选项,如果用户选择“其他”,我希望他们描述它们的含义。像这样: impact = wtforms.SelectMultipleField('What is the expected impact?', choices=[('Sales', 'Sales'),

我刚开始使用Flask WTF表单。我可以和他们一起做我需要的一切,除了我似乎不知道一件事。我有一个多选字段,向用户显示各种选项,如果用户选择“其他”,我希望他们描述它们的含义。像这样:

 impact = wtforms.SelectMultipleField('What is the expected impact?',
                           choices=[('Sales', 'Sales'),
                                    ('Lift', 'Lift'),
                                    ('Other', 'Other')]
我不知道当它不是一个具有自己ID的独立字段,而只是数组中的一个成员时,它是否可能。你能帮忙吗

编辑

以下是我按照下面的建议尝试的内容-在选择或取消选择“其他”没有任何区别的意义上,它不起作用:

app.py:

app.route('/', methods=['GET', 'POST'])
def home():
     form = MyForm()
     other_enable = False

       if form.validate_on_submit():

          name = form.name.data
          email = form.email.data
          impact1 = form.impact.data
          impact = ''.join(str(e) for e in impact1)

          if ("Other" in impact):
              other_enable = True
          impact_other = form.impact_other.data
          return redirect(url_for('home'))
       return(render_template('home.html', form=form, other_enable=other_enable))
和templates/home.html包含

{% extends "base.html" %}

{% import "bootstrap/wtf.html" as wtf %}

<center>

  <div id="someid" onchange='myFunction(other_enable)'>{{ wtf.quick_form(form) }}</div>

</center>

{% endblock %}

<script>
     function myFunction(other_enable) {
         var theother = document.getElementById("otherField");

         if (other_enable == true){
            theother.style.display = "block";
        } else {
            theother.style.display = "none";
        }
    }
 </script>
{%extends“base.html”%}
{%import“bootstrap/wtf.html”作为wtf%}
{{wtf.quick_form(form)}
{%endblock%}
功能myFunction(其他功能启用){
var theother=document.getElementById(“otherField”);
如果(其他_启用==真){
theother.style.display=“块”;
}否则{
theother.style.display=“无”;
}
}

您必须在表单中添加另一个字段,如
TextField()
,并使其成为
validator.Optional()

然后使用简单的javascript和
onchange
事件,默认情况下,您可以
显示:无
此字段,如果用户选择
其他
显示它

最后,如果希望强制用户“描述他们的意思”,可以在表单类中添加以下方法:

def validate(self):
    """ Add custom validators after default validate
    """
    success = super(YourFormClass, self).validate()

    if 'Other' in self.impact.data and len(self.impact_other.data) < 1:
        success = False
        self.impact.errors.append(gettext('Please fill impact_other field if you had selected "Other"'))

    return success
def验证(自):
“”“在默认验证之后添加自定义验证程序
"""
success=super(YourFormClass,self).validate()
如果self.impact.data中的'Other'和len(self.impact_Other.data)<1:
成功=错误
self.impact.errors.append(gettext('如果选择了“其他”,请填写impact_other字段)))
回归成功
(假设您创建的其他字段名为
impact\u other

编辑:我稍微修改了validate()函数,用于处理SelectMultilpleField而不是SelectField

接下来,您不必将
other\u enable
变量传递给模板,默认情况下,如果未选择任何内容,您应该隐藏
otherField
,因此您不仅需要在更改时运行js,还需要在加载页面后运行js

如果在字段
impact
中选择了“Other”,则只需检查js函数,如果是,则显示字段。在检测JS中的选定值时,您可以查看此问题以获得更多帮助:


此外,如果表单验证失败,您必须执行
form=MyForm(request.form)
以保存用户输入

谢谢Calumah,我试过了,但没有成功(见我上面的编辑),也许我不明白如何正确地执行你的建议?@user3490622我已经更新了我的答案,希望这能对你有所帮助