wtforms-alchemy - 如何使用关系数据预先填充表单?

时间:2016-11-11 19:02:03

标签: python flask-sqlalchemy wtforms flask-wtforms

所以...

此:

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怎么样?

以上代码不预先填充关系字段;它们出现但是留空了。只有db.Column字段预先填充了值,无论我是否强制在model_dictonary中包含关系值(例如,model_dictionary [' key_from_other_object'] =关联值)。

这可以实现吗? - 找不到任何东西......

修改 我解决了我最初的问题:

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 个答案:

答案 0 :(得分:1)

使用SelectMultipleField和SelectField来咆哮错误的树。

相反,

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

这篇文章有助于展示用法,@ WTForms QuerySelectMultipleField Not sending List

解决了我的问题..

..结束了

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