2016-11-11 63 views
0

所以...wtforms-alchemy - 如何预先填充关系数据的表单?

此:

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_dictonary中包含关系值(例如,model_dictionary ['key_from_other_object'] = associated value),只有db.Column字段预先填充了值。

这可以完成吗? --Can't找到这样的东西..

编辑: 我解决了我最初的问题:

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

回答

1

就找使用SelectMultipleField和SelectField错了..

相反,

wtforms_alchemy.fields.QuerySelectMultipleField @https://media.readthedocs.org/pdf/wtforms-alchemy/latest/wtforms-alchemy.pdf

这个帖子,这有助于展示使用,@WTForms QuerySelectMultipleField Not sending List

解决我的问题..

..ended了

class LocationForm(ModelForm): 
    class Meta: 
     model = models.Location 

    events = wtforms_alchemy.fields.QuerySelectMultipleField('Event', 
     query_factory=lambda: models.Event.query.order_by(models.Event.name).all(), 
     get_label= lambda x: x.name, 
     option_widget=widgets.CheckboxInput(), 
     widget=widgets.ListWidget(prefix_label=False) 
     )