【发布时间】:2016-12-13 02:46:35
【问题描述】:
所以...
这个:
model_dictionary = model.as_dict() # some kind of dictionary
form = TheModelsForm(**model_dictionary) # https://wtforms-alchemy.readthedocs.io/en/latest/advanced.html
form.populate_obj(model)
return form
这让我用模型中的字段预先填充模型的表单,这些字段是 db.Columns.. 那么.. 模型上的 db.relationships 呢?
上面的代码没有预先填充关系字段;他们出现但留空。无论我是否强制在 model_dictionary 中包含关系值(例如,model_dictionary['key_from_other_object'] = associated value),都只有 db.Column 字段预先填充了值。
这可以实现吗? --在这上面找不到任何东西..
编辑: 我解决了我最初的问题:
form = TheModelsForm(obj=model)
form.populate_obj(model)
return form
现在我正在尝试弄清楚如何让位置模型上的事件真正显示在位置表单上...
class Event(Base):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String())
location_id = db.Column(db.Integer, db.ForeignKey('location.id'))
class Location(Base):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String())
events = db.relationship('Event', backref=db.backref('events'))
我确定我注释掉的所有内容都不起作用是有逻辑的原因。我得到“NoneType”对象不可迭代
class EventForm(ModelForm):
class Meta:
model = models.Event
location_id = fields.SelectField(u'Location', coerce=int)
class LocationForm(ModelForm):
class Meta:
model = models.Location
#events = fields.SelectField(u'Event', choices=[(g.id, g.selector) for g in models.Event.query.all()], coerce=int)
# events = fields.SelectMultipleField('Event',
# choices=[(g.id, g.selector) for g in models.Event.query.all()],
# coerce=int,
# option_widget=widgets.CheckboxInput(),
# widget=widgets.ListWidget(prefix_label=False)
# )
#events = ModelFieldList(fields.FormField(EventForm))
【问题讨论】:
标签: python flask-sqlalchemy wtforms flask-wtforms