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

问题描述

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

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

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

编辑

这是我按照以下建议尝试的方法-从选择或取消选择“其他”没有区别的意义上说,它不起作用:

应用程序.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>

标签: flaskflask-wtforms

解决方案


您必须在表单中添加另一个字段,例如TextField()并制作它validator.Optional()

然后使用简单的 javascript 和onchange事件,您可以display:none默认使用此字段,如果用户选择Other显示它。

最后,如果你想强制用户“描述他们的意思”,你可以在 YourForm 类中添加这个方法:

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() 函数以使用 SelectMultilpleField 而不是 SelectField

接下来,您不必将other_enable变量传递给您的模板,默认情况下,如果未选择任何内容,您应该 hide otherField,因此您不仅需要运行 js,还需要在页面加载后运行。

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

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


推荐阅读