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

Flask WTF forms: can a new field be shown if a user selects a specific choice in SelectMultipleField?

我刚开始使用 Flask WTF 表单。我可以用它们做我需要做的一切,除了我似乎无法弄清楚一件事。我有一个多项选择字段,向用户显示各种选项,如果用户选择 "other",我希望他们描述他们的意思。像这样:

 impact = wtforms.SelectMultipleField('What is the expected impact?',
                           choices=[('Sales', 'Sales'),
                                    ('Lift', 'Lift'),
                                    ('Other', 'Other')]

我不知道当它不是一个具有自己的 ID 的独立字段而只是数组中的一个成员时是否可行。你能帮忙吗?

编辑

这是我按照下面的建议尝试的方法 - 它在选择或取消选择 "Other" 没有区别的意义上不起作用:

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>

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

然后使用简单的 javascript 和 onchange 事件你可以 display:none 默认情况下这个字段,如果用户 select Other 显示它。

最后,如果你想强制用户 "describe what they mean" 你可以在 YourForm class 中添加这个方法:

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

(假设您创建的其他字段名为 impact_other

编辑:我稍微修改了我的 validate() 函数以使用 SelectMultipleField 而不是 SelectField

接下来,您不必将 other_enable 变量传递给您的模板,默认情况下,如果没有 selected 您应该隐藏 otherField,因此您需要 运行 你的 js 不仅在 onchange 上而且在页面加载后也是如此。

如果 'Other' 在您的字段 impact 中被 select 编辑,您只需检查您的 js 函数,如果是,则显示您的字段。您可以查看此问题以获得更多有关检测 JS 中的 selected 值的帮助:here

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