我正在我的 Flask 应用程序中构建一个表单,并希望用户能够从 <select>
中选择一个选项。菜单。
例如:
<select>
<option>Banana</option>
<option>Pineapple</option>
</select>
我当前的“HTML”是
<form action="{{ url_for('contact') }}" method=post>
{{ form.hidden_tag() }}
{{ form.name.label }}
{{ form.name }}
{{ form.company.label }}
{{ form.company }}
{{ form.email.label }}
{{ form.email }}
{{ form.phone.label }}
{{ form.phone }}
{{ form.message.label }}
{{ form.message }}
{{ form.submit }}
</form>
此表单的我的 Python 类是:
class ContactForm(Form):
partner_type = SelectField(
u'Industry Type',
choices = [('Software', 'software'), ('Sales', 'sales')]
)
name = TextField("Name", [validators.Required("Please enter your full name.")])
email = TextField("Email", [validators.Required("Please enter a valid email i.e. you@yourdomain.com"), validators.Email()])
phone = TextField("Phone", [validators.Required("Please enter a valid phone number.")])
company = TextField("Company", [validators.Required("Please enter your company name.")])
message = TextAreaField("Message", [validators.Required("Please include a message regarding this submission.")])
submit = SubmitField("Send")
这对于文本字段和提交按钮都非常有效,但我似乎不知道如何正确渲染 <select>
表单的选项。我尝试遵循上面的语法:
{{ form.industry_type.label }}
{{ form.industry_type }}
但这没有用。它只是添加了标签,没有下拉选择器。有没有正确的方法将其添加到 DOM 中?这些选项是静态的预设选项,因此我尝试呈现的列表没有任何动态或复杂的内容。
感谢您的帮助。我对 Python 还很陌生,所以我仍在弄清楚很多事情。
最佳答案
您应该使用:
{{ form.partner_type.label }}
{{ form.partner_type }}
而不是:
{{ form.industry_type.label }}
{{ form.industry_type }}
表单中的字段名称是分配给它的变量名称,而不是 SelectField 构造函数中的标签。
关于python - 如何将 Flask/WTForms SelectField 添加到我的 HTML 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44055471/