使用wtforms SelectField从表单中获取选定的文本 [英] Get selected text from a form using wtforms SelectField

查看:436
本文介绍了使用wtforms SelectField从表单中获取选定的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是使用 wtforms SelectField 的问题。



提交表单后,我希望提取选定的文本。



我有以下形式: p>

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

以下是视图:

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

使用 test.hour = form.hour.name 获得属性 name 8am 如果第一个选项被选中)。

这应该怎么做?

解决方案

在表单中定义全局选项:



<$ ($'$'$'$'$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b hour = SelectField(u'Hour',choices = HOUR_CHOICES)

从窗体中导入它,将其转换来自.forms的

 导入HOUR_CHOICES 

hour_display = dict(HOUR_CHOICES).get(form .hour.data)


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.

解决方案

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)

这篇关于使用wtforms SelectField从表单中获取选定的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆