Is there a way to create a datalist field in Flask WTForms?
Asked Answered
G

2

9

Does anyone know of a way to create a datalist field using WTForms in Flask?

I know how to create a SelectField but I need to allow the user to enter their own value if it isn't in the list.

This is what I want to do http://www.w3schools.com/tags/tag_datalist.asp

Thanks

Gillum answered 27/1, 2016 at 22:47 Comment(5)
Probably related: Security question & answer. What questions do you ask?Grice
@MartinThoma How is a post about security questions relevant to creating a datalist field?Gillum
2020 and still no reasonable way of doing some widget way to make SelectField renders options using <datalist></datalist> ?Sundin
at the moment I am too lazy to dig into it and pick select2Sundin
I have file an issue on WTForms on github github.com/wtforms/wtforms/issues/653Sundin
E
16

You create a simple StringField in your view.

autocomplete_input = StringField('autocomplete_input', validators=[DataRequired()])

In your template you call the field and add the list parameter (remember to pass the entries to your template):

{{form.autocomplete_input(list="id_datalist")}}
<datalist id="id_datalist">
{% for entry in entries %}
<option value={{ entry }}>
{% endfor %}
</datalist>
Eldrid answered 29/3, 2016 at 11:55 Comment(0)
L
0

In my case it was easier to use JS library called Select2

It connverts regular <select> tag into searchable interactive widget

Here is code from my template

{% block content %}
{# Add styles and js libs #}
<script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js" defer></script>

{# Old forms initialization here #}
{{super()}}

{# Activate Select2 #}
<script>
    $(document).ready(function() {
        $('#select-tag-id').select2();
    });
</script>
{% endblock %}

Also take a look at docs with examples

Logion answered 10/8, 2023 at 22:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.