Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...