我正在创建一个烧瓶表单,该容器需要根据Flask中的其他下拉列表选择字段显示一个下拉列表。我能够使用HTML做到这一点,但是发现以Flask形式很难做到这一点。
routes.py:
class RegistrationForm(FlaskForm):
category = SelectField('Category', choices = [('Clothes', 'Clothes'), ('Watch', 'Watch')])
subcategory = SelectField('Sub Category', choices = [('USPA', 'USPA'), ('LEE', 'LEE'), ('FOSSIL', 'FOSSIL'), ('TITAN', 'TITAN')])
submit = SubmitField('Register')
HTML:
<form action="" method="post">
{{ form.hidden_tag() }}
<p>
<p>
{{ form.category.label }}<br>
{{ form.category }}<br>
{% for error in form.category.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ form.subcategory.label }}<br>
{{ form.subcategory }}<br>
{% for error in form.subcategory.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>{{ form.submit() }}</p>
</form>
我要映射链接:
衣服:USPA,李
手表:化石,泰坦
但是以表格的形式我得到了所有选择。我需要基于所选类别的子类别。
答案 0 :(得分:2)
由于这是客户端的动态功能,您将需要使用Javascript。
我个人认为,最简单的方法是预先静态配置烧瓶形式:
class RegistrationForm(FlaskForm):
category = SelectField('Category', choices = [('Clothes', 'Clothes'), ('Watch', 'Watch')])
subcategory_clothes = SelectField('Sub Category', choices = [('USPA', 'USPA'), ('LEE', 'LEE')], validators=[Optional()])
subcategory_watches = SelectField('Sub Category', choices = [('Titan', 'Titan'), ('Fossil', 'Fossil')], validators=[Optional()])
submit = SubmitField('Register')
然后使用JavaScript if语句显示取决于初始组合框值的一个或其他组合框。您将需要一个javascript事件挂钩来检测类别的更改,或使用Vue.js之类的框架。
此处有一个JavaScript钩子示例https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onchange
您可以在HTML中添加一个javascript函数,以根据另一个复选框的值显示其中一个框:
<script>
function myFunction() {
let box_value = document.getElementById("category").value;
if (box_value === "Clothes") {
document.getElementById("subcategory_clothes").style.display = "initial"
document.getElementById("subcategory_watches").style.display = "none"
} else {
document.getElementById("subcategory_clothes").style.display = "none"
document.getElementById("subcategory_watches").style.display = "initial"
}
}
</script>
您可以在Python中添加render_keyword参数,以便它填充HTML中的事件挂钩:
category = SelectField('Category', choices = [('Clothes', 'Clothes'), ('Watch', 'Watch')], render_kw={'onchange': "myFunction()"})