如何从flask wtf中的SelectField获取选定的数据

时间:2014-09-04 07:58:20

标签: flask flask-wtforms

select = SelectField("City")

form.select.choices = [(places['name'], places['name']) for places in place]

现在我想从selectfield中选择数据

1 个答案:

答案 0 :(得分:2)

您可以覆盖表单类初始化方法。

我给出的例子和清楚的解释:

models.py

class Place(db.Model):
    name = db.Column(db.String(40), unique=True)

forms.py

from flask.ext.wtf import Form
from wtforms import SelectField

class PlaceForm(Form):
    name_list = SelectField(u'Choose the place')

    def __init__(self, *args, **kwargs):
        self.name_list.choices = [(obj.id, obj.name) for obj in Place.query.order_by('name')]

在模板

 <div class="control-group{% if form.errors.name_list %} error{% endif %}">
                            {{ form.name_list(placeholder="--select--") }}
                            {% for error in form.errors.name_list %}
                                <span class="help-inline">{{error}}</span><br>
                            {% endfor %}

</div>
make sure you are passing the form to this template in your views.py.

这应该有用。我想你可以很好地理解这个片段。