Flask WTF表单:如果用户在SelectMultipleField中选择特定选项,是否可以显示新字段? [英] Flask WTF forms: can a new field be shown if a user selects a specific choice in SelectMultipleField?
问题描述
我刚刚开始使用Flask WTF表单.我可以和他们一起做所有我需要的事情,除了我似乎无法弄清楚一件事.我有一个选择项字段,向用户显示各种选项,如果用户选择其他",我希望他们描述它们的含义.像这样:
I just started using Flask WTF forms. I can do everything that I need with them except I can't seem to figure out one thing. I have a multiple choice field presenting various options to the user, and if the user selects "other", I want them to describe what they mean. Like this:
impact = wtforms.SelectMultipleField('What is the expected impact?',
choices=[('Sales', 'Sales'),
('Lift', 'Lift'),
('Other', 'Other')]
我不知道它是否不是一个具有自己ID的独立字段,而只是数组中的一个成员,是否有可能.你能帮忙吗?
I don't know if it's even possible when it's not an independent field with its own ID but just a member within an array. Could you please help?
编辑
这是我按照下面的建议尝试的操作-从选择或取消选择其他"没有区别的意义上说,它没有用:
here's what I tried following the suggestion below - it didn't work in the sense that selecting or unselecting "Other" makes no difference :
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包含
and templates/home.html contains
{% 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()代码>.
You have to add another field in your form like TextField()
and make it validator.Optional()
.
然后使用简单的javascript和 onchange
事件,默认情况下,如果用户选择 Other
显示此字段,则可以 display:none
该字段.
Then with simple javascript and onchange
event you can display:none
this field by default and if user select Other
show it.
最后,如果要强制用户描述他们的意思",则可以在YourForm类中添加以下方法:
At the end if you want force user to "describe what they mean" you could add in YourForm class this method :
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
)
(assuming other field you created is named impact_other
)
我稍微修改了validate()函数以使用SelectMultilpleField而不是SelectField
EDIT : I modified slightly my validate() function for working with SelectMultilpleField instead of SelectField
接下来,您不必将 other_enable
变量传递给模板,默认情况下,如果未选择任何内容,则应隐藏 otherField
,因此您需要运行js不仅是onchange,而且页面加载后也是如此.
Next, you don't have to pass other_enable
variable to your template, by default if nothing is selected you should hide otherField
, so you need to run your js not only onchange but also after page loaded.
如果您在字段 impact
中选择了其他",则只需检查js函数,如果是,则显示您的字段.您可以查看此问题以获取更多有关检测JS中选定值的帮助:
You just have to check into your js function if 'Other' is selected in your field impact
, if yes then show your field. You can look this question for more help at detecting selected values in JS : here
此外,如果表单验证失败,您还必须执行 form = MyForm(request.form)
来保存用户输入.
Additionally you have to do form = MyForm(request.form)
to save user input if form validate fail.
这篇关于Flask WTF表单:如果用户在SelectMultipleField中选择特定选项,是否可以显示新字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!