2

So, I am building a web form containing a SelectField using FlaskForm and wtforms. When the user submits the form, I can read StringFields without any problem, however, the SelectField's value is always None.

I've been looking to fix this problem for several hours now but could find neither an answer nor an explanation of what is going wrong in my code.

I looked at following threads without success:

and many more, that I couldn't find again. I also read through the documentation and these examples.

Here is some code to reproduce the problem:

from flask import Flask, url_for, redirect, request, render_template_string
from flask_wtf import FlaskForm
from wtforms import SelectField, SubmitField

app = Flask(__name__)
app.config["SECRET_KEY"] = "very_secret"

# basic html template
my_html = """
<div class="content-section">
        <form method="POST" action=".">
            {{form.hidden_tag()}}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">New Task</legend>


                <div class="form-group">
                    {{ form.select.label(class="form-control-label")}}
                    <select class="form-control" id="continent_selector">
                        {% for choice in form.select.choices %}
                            <option value="{{ choice[1] }}">{{ choice[0] }}</option>
                        {% endfor %}
                      </select>
                </div>


            </fieldset>
            <div class="form-group">
                {{ form.submit(class="btn btn-outline-info")}}
            </div>
        </form>
    </div>
"""


class TaskForm(FlaskForm):
    tuple_list = [("Choice_0", 0), ("Choice_1", 1)]
    select = SelectField("select", choices=tuple_list)
    submit = SubmitField("Create Task")


@app.route("/", methods=["GET", "POST"])
def new_task():
    form = TaskForm()
    if request.method == "POST": 
        print("-------------FORM--------------")
        print(form.data)
        print("-------------END--------------")
        return str(form.select.data)
    return render_template_string(my_html, title="New Task", form=form)


if __name__ == "__main__":
    app.run(debug=True)

Printing out the form.data looks like this:

{'select': 'None', 'submit': True, 'csrf_token': 'some_hash'}

It would be great if someone could point out to me what I'm doing wrong :)

fav
  • 31
  • 4

1 Answers1

2

Your select tag needs a name. Replace:

<select class="form-control" id="continent_selector">

With:

<select class="form-control" id="continent_selector" name="select">
truth
  • 1,156
  • 7
  • 14