flask - 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>
解决方案
您必须在表单中添加另一个字段,例如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)
保存用户输入。
推荐阅读
- javascript - React 组件在选项卡之间来回移动时加载数据两次
- flutter - Flutter Web:使用 HtmlElementView、IFrameElement、registerViewFactory 实现的解决方案在 ios 中不起作用
- javascript - JavaScript,eccrypto.encrypt() 在对值进行十六进制处理后给出 [object object]
- python - 将嵌套列表转换为列表显示不可散列的类型
- c# - VisualStudio 未找到命名空间
- android - 如何在 android:updatePeriodMillis="0" 时从 Flutter 更新 Android 小部件?
- python - 使用 pip 安装时出错 - 请检查代理 URL。它格式不正确,可能缺少主机
- rust - Clippy 抱怨严格的 f32 比较
- javascript - 更新数组中对象的值 - 反应钩子
- html - Flexbox溢出自动:拉伸孩子