gpt4 book ai didi

python-3.x - 根据 flask 中的其他选择选项显示选择字段

转载 作者:行者123 更新时间:2023-12-03 16:25:01 26 4
gpt4 key购买 nike

我正在创建一个 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')

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>

我想要映射链接:

Clothes : USPA, LEE

Watch : FOSSIL, TITAN

但在表格中我得到了所有选项。我需要基于所选类别的子类别。

最佳答案

由于这是客户端的动态功能,您需要使用 Javascript。

我个人认为最简单的方法是预先静态配置你的 flask 表单:

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 事件 Hook 来检测类别的更改,或使用 Vue.js 等框架。

这里有一个 javascript 钩子(Hook)的例子 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 中的事件 Hook :

category = SelectField('Category', choices = [('Clothes', 'Clothes'), ('Watch', 'Watch')], render_kw={'onchange': "myFunction()"})

关于python-3.x - 根据 flask 中的其他选择选项显示选择字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58841634/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com