Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wtforms TextField/SearchField with autocompletion for flask app (similar to a google search bar)

I am looking for a mixture between SelectField and Textfield of wtforms where it is possible to input a String which is validated and autocompleted from a given list of options, like the choice argument in SearchField.

Currently I have this implementation, which is just a dropdown menu, but i want the user to be able to type any string. While typing the string all matching options should be shown in a dropdown list like in a google search bar.

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()])
like image 512
gustavz Avatar asked Jan 31 '26 03:01

gustavz


1 Answers

Select2 JQuery library might be what you want. Unfortunately it is not possible to achieve your goal in Flask itself. JS is needed.

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()])

Template:

<!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>
like image 153
stasiekz Avatar answered Feb 02 '26 15:02

stasiekz