使用 WTForms 的动态选择字段未更新 [英] Dynamic select field using WTForms not updating
本文介绍了使用 WTForms 的动态选择字段未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 wtforms 和 sqlalchemy 创建一个动态选择字段,但是当从数据库中插入或删除项目时它不会更新.这是我的代码:
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)]
)
和数据库模型:
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.
推荐答案
您应该在创建表单对象时初始化表单选择:
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)]
或者在视图中:
form = UserForm()
form.job.choices = [(a.id, a.name) for a in Job.query.order_by(Job.name)]
这篇关于使用 WTForms 的动态选择字段未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文