Dynamic select field using WTForms not updating

此生再无相见时 提交于 2019-11-27 14:15:52

问题


I'm trying to make a dynamic select field using wtforms and sqlalchemy, but it doesn't update when an item is inserted or deleted from the database. Here's my code:

class UserForm(Form):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    job = SelectField(
        'Job',
        validators=[DataRequired()],
        choices=[(a.id, a.name) for a in Job.query.order_by(Job.name)]
    )

And the database model:

class Job(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String)

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Job %s>' % self.name

It successfully shows the jobs in the select field, but if you modify the table, it doesn't update, except if you completely restart the application.


回答1:


You should initialize the form choices when the form object is created:

class UserForm(Form):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    job = SelectField(
        'Job',
        validators=[DataRequired()]
    )

    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)
        self.job.choices = [(a.id, a.name) for a in Job.query.order_by(Job.name)]

Or in the view:

form = UserForm()
form.job.choices = [(a.id, a.name) for a in Job.query.order_by(Job.name)]



回答2:


It's worth mention that part of the answer of @plaes is wrong

def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)
        self.job.choices = [(a.id, a.name) for a in Job.query.order_by(Job.name)]

in the init func we should call super first .then use self.job.choices or it will not work..

see my question here flask wtforms selectfield choices not update



来源:https://stackoverflow.com/questions/31619747/dynamic-select-field-using-wtforms-not-updating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!