Question: Flask WTForms SelectField get currently selected item

Question

Flask WTForms SelectField get currently selected item

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

I am having difficulty getting the currently selected item in a WTForms page in a Flask app on submit. The form.tableselector.data 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:

views.py

from flask import session

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

form.py

class MyBaseForm(Form):
    #see https://wtforms.readthedocs.io/en/latest/csrf.html
    class Meta:
        csrf = True
        csrf_class = SessionCSRF
        csrf_secret = app.config.get('SECRET_KEY')

        @property
        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

tableview.html

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

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
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

Use:

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