Question: Flask WTForms SelectField get currently selected item


Flask WTForms SelectField get currently selected item

Answers 1
Added at 2017-01-02 15:01

I am having difficulty getting the currently selected item in a WTForms page in a Flask app on submit. The value is always equal to 1 on submit, no matter which item in the SelectField is selected (and all choices have a unique table id from 1-10 of the form (1, 'table_name') where 1 is an integer.

Here is current code:

from flask import session

def view(self):
    form = Tableset(request.form)
    if request.method == 'POST' and form.validate(): always returns 1 no matter which item is selected?
        session['table_id'] =

class MyBaseForm(Form):
    class Meta:
        csrf = True
        csrf_class = SessionCSRF
        csrf_secret = app.config.get('SECRET_KEY')

        def csrf_context(self):
            return session

class Tableset(MyBaseForm):
    tableselector = SelectField(label = 'Table', choices = [], coerce=int, id='select_table')
    submit = SubmitField('Submit')

    def validate(self):
        if len(self.tableselector.choices) == 0:
            return False
        return True


<form role="form" action="{{ url_for('app.table_view') }}" method="post">
    {{ form.csrf_token }}
    <div class="form-group">
    {{ form.tableselector.label }} 
    {{ form.tableselector }}

I note that on debug for the form the wtf Meta object csrf property is equal to True so I know CSRF is working.

Answers to

Flask WTForms SelectField get currently selected item

nr: #1 dodano: 2017-01-03 04:01

The problem was I was calling the wrong parameter in the view.

see here: How to obtain values of request variables using Python and Flask


if request.method == 'POST' and form.validate():
    session['table_id'] = request.form.get('tableselector')
Source Show
◀ Wstecz