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
412 views
in Technique[技术] by (71.8m points)

python - Dynamic select field using WTForms not updating

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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

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

...