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.
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.
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):
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.
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.
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)
It was answered as a comment, so I'm writing here.
Use form.hour.data
to get the value instead of the name.
If you don't need the choice indexes, is much more simpler:
class TestForm(Form):
hour = SelectField(u'Hour', choices=[('8am', '8am'), ('10am', '10am') ])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With