【问题标题】:Flask WTF forms: can a new field be shown if a user selects a specific choice in SelectMultipleField?Flask WTF 表单:如果用户在 SelectMultipleField 中选择特定选项,是否可以显示新字段?
【发布时间】:2018-05-25 01:20:51
【问题描述】:

我刚开始使用 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>

【问题讨论】:

    标签: flask flask-wtforms


    【解决方案1】:

    您必须在表单中添加另一个字段,例如 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 变量传递给您的模板,默认情况下,如果未选择任何内容,则应隐藏otherField,因此您不仅需要运行js,还需要在页面加载后运行。

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

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

    【讨论】:

    • 谢谢 Calumah,我试过了,但没有用(请参阅上面的编辑),也许我不明白如何正确执行您的建议?
    • @user3490622 我已经更新了我的答案,希望对你有帮助
    猜你喜欢
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 2016-07-06
    相关资源
    最近更新 更多