3
select = SelectField("City")

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

Now I want to get selected data from selectfield

1 Answer 1

2

You can override the form class initializer method.

I am giving the example and clear explanation:

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')]

in templates

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

This should work.I think you could understand this snippet well.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.