Shi*_*aha 3 cascadingdropdown flask python-3.x flask-wtforms
我正在创建一个 Flask 表单,我需要在 Flask 中显示基于其他一些下拉选择字段的下拉列表。我可以用 HTML 做到这一点,但发现很难在 Flask 形式中做到同样的事情。
路线.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')
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
我想要映射链接:
衣服:USPA、LEE
手表:化石、泰坦
但在形式上我得到了所有的选择。我需要基于所选类别的子类别。
由于这是客户端的动态功能,因此您需要使用 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')
Run Code Online (Sandbox Code Playgroud)
然后使用 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>
Run Code Online (Sandbox Code Playgroud)
您可以在 Python 中添加 render_keyword 参数,以便它填充 HTML 中的事件挂钩:
category = SelectField('Category', choices = [('Clothes', 'Clothes'), ('Watch', 'Watch')], render_kw={'onchange': "myFunction()"})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8175 次 |
| 最近记录: |