我正在寻找 wtforms 的 SelectField 和 Textfield 之间的混合体,在其中可以输入一个字符串,该字符串从给定的选项列表中验证并自动完成,例如 SearchField 中的选择参数。
目前我有这个实现,它只是一个下拉菜单,但我希望用户能够键入任何字符串。在键入字符串时,所有匹配选项都应显示在下拉列表中,就像在谷歌搜索栏中一样。
possible_names = {0:'hans', 1:'sepp', 3:'max'}
class ReusableForm(Form):
name = SelectField("Enter a Name",
choices=[(uuid, name) for uuid, name in possible_names.items()],
validators=[validators.InputRequired()])
最佳答案
Select2 JQuery library可能是你想要的。不幸的是,不可能在 Flask 本身中实现您的目标。需要JS。
from flask import Flask, render_template
from flask_wtf import Form
from wtforms import SelectField, validators
app = Flask(__name__)
app.config['SECRET_KEY'] = 'YOUR SECRET KEY'
possible_names = {'0': 'hans', '1': 'sepp', '3': 'max'} # options should be str so that empty choice option is valid
class ReusableForm(Form):
name = SelectField("Enter a Name",
choices=[("", "")] + [(uuid, name) for uuid, name in possible_names.items()], # [("", "")] is needed for a placeholder
validators=[validators.InputRequired()])
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
</head>
<body>
<form method="POST">
{{ form.hidden_tag() }}
<div style="width: 220px">
{{ form.name }}
</div>
<button>Submit</button>
</form>
<script>
$(document).ready(function() {
$('#name').select2({ // init Select2 on form's name field
placeholder: "{{ form.name.label.text }}",
allowClear: true,
"width": "style"
});
});
</script>
</body>
</html>
关于python - wtforms TextField/SearchField,具有 flask 应用程序的自动完成功能(类似于谷歌搜索栏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58354678/