我正在尝试使用wtforms和sqlalchemy创建一个动态选择字段,但是当从数据库中插入或删除项目时它不会更新。这是我的代码:
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
它成功显示了选择字段中的作业,但是如果您修改了表,则它不会更新,除非您完全重新启动应用程序。
答案 0 :(得分:14)
您应该在创建表单对象时初始化表单选项:
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)]
答案 1 :(得分:3)
值得一提的是@plaes的部分答案是错误的
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)]
在init函数中我们应该首先调用super。然后使用self.job.choices,否则它将无效..