【问题标题】:wtforms-alchemy - what about pre-populating the form with relationship data?wtforms-alchemy - 用关系数据预先填充表单怎么样?
【发布时间】: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


    【解决方案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)
            )
    

    【讨论】:

      猜你喜欢
      • 2013-03-08
      • 2016-06-23
      • 2017-08-16
      • 1970-01-01
      • 2021-06-30
      • 2013-10-04
      • 1970-01-01
      • 2012-08-14
      • 1970-01-01
      相关资源
      最近更新 更多