python - wtforms TextField/SearchField 与烧瓶应用程序的自动完成(类似于谷歌搜索栏)
问题描述
我正在寻找 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 库可能是您想要的。不幸的是,在 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>
推荐阅读
- rest - REST:当请求更改多个实体的状态时返回什么?
- java - java中SELECT的方法:返回什么以及如何关闭资源?
- redis - Windows 上的 Redis 抛出错误:READONLY You can't write against a read only slave., sPort: xxxxx , LastCommand:
- javascript - 如何使用 React Router 获取多个参数
- javascript - 带有 setTimeout 延迟无限循环的 Vanilla Javascript 信息代码
- .net - 如何编写后控制器操作方法以在.Net Core Web API中调用外部api
- ios - api 请求之间的冷却时间
- typescript - 带有方法的 TypeScript 类型保护属性
- apache-spark - PySpark:是否有可能根据非 Null 值创建动态数量的 DataFrame
- tsql - SQL Server:如何按特定顺序显示我的数据