Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected text from a form using wtforms SelectField

This is a question upon the use of wtforms SelectField.

Once the form submitted, I wish to extract selected text.

I have the following form:

from wtforms import Form, SelectField
class TestForm(Form):
     hour = SelectField(u'Hour', choices=[('1', '8am'), ('2', '10am') ])

Here's the view:

@app.route('/', methods=['GET', 'POST'])
def test_create():
form =TestForm(request.form)
if request.method == 'POST' and form.validate():
    test = Test()
    form.populate_obj(test)
    test.hour=form.hour.name
    db.session.add(test)
    db.session.commit()
    return redirect(url_for('test_create'))
return render_template('test/edit.html', form=form)

With test.hour=form.hour.name I obtain the attribute name (no surprise...), whilst I need the text (let's say 8am if the first option is chosen).

How should this be possible ? Thanks for any hint.

like image 573
mannaia Avatar asked Jan 19 '14 13:01

mannaia


People also ask

What does WTForms stand for?

WTF stands for WT Forms which is intended to provide the interactive user interface for the user. The WTF is a built-in module of the flask which provides an alternative way of designing forms in the flask web applications.

What is FlaskForm?

FlaskForm Class. Flask provides an alternative to web forms by creating a form class in the application, implementing the fields in the template and handling the data back in the application. A Flask form class inherits from the class FlaskForm and includes attributes for every field: class MyForm(FlaskForm):

What is Stringfield?

The string field is used for allowing users to enter unformatted text information into your form in a limited fashion. Creating multiple strings is useful for collecting directed information, such as answers from your user requiring single words or brief sentences.

How do I import WTForms into a flask?

Step 1 — Installing Flask and Flask-WTF In this step, you'll install Flask and Flask-WTF, which also installs the WTForms library automatically. With your virtual environment activated, use pip to install Flask and Flask-WTF: pip install Flask Flask-WTF.


3 Answers

Define choices global in forms:

HOUR_CHOICES = [('1', '8am'), ('2', '10am')]

class TestForm(Form):
     hour = SelectField(u'Hour', choices=HOUR_CHOICES)

import it from forms, convert it to dict:

from .forms import HOUR_CHOICES

hour_display = dict(HOUR_CHOICES).get(form.hour.data)
like image 113
iMom0 Avatar answered Nov 03 '22 04:11

iMom0


It was answered as a comment, so I'm writing here.

Use form.hour.data to get the value instead of the name.

like image 7
iurisilvio Avatar answered Nov 03 '22 04:11

iurisilvio


If you don't need the choice indexes, is much more simpler:

class TestForm(Form):
  hour = SelectField(u'Hour', choices=[('8am', '8am'), ('10am', '10am') ])
like image 4
Hernán Acosta Avatar answered Nov 03 '22 04:11

Hernán Acosta