【问题标题】:on_form_prefill delete all fields values if it executes form.processon_form_prefill 如果执行 form.process 则删除所有字段值
【发布时间】:2015-08-04 05:22:52
【问题描述】:

我想覆盖下面显示的Matriline 模型的形式。

首先我添加一个额外的字段clan,然后在on_form_prefill 中重置该字段的选项和默认值(只是测试)。

不调用form.process,选项设置为我的新选项,但未选择默认选项。

如果调用form.process,选项将设置为我的新选项并选择默认选项,但所有其他字段都将被删除。

有人可以帮忙吗?

views.py

class MatrilineAdmin(sqla.ModelView):

    form_extra_fields = {
        'clan': SelectField('Clan',
            coerce=int,
            choices=[ (c.id, c.name) for c in Clan.query.all()])
    }
    create_template = 'admin/create.html'
    edit_template = 'admin/edit.html'

    def on_form_prefill(self, form, id):
        form.clan.choices = [(1, "first"),(2,"second")]
        form.clan.default = 2
        form.process() # if commented, set choices but does not set default
                       # else set choices and default but delete all the other fields values (name and pod_id)

models.py

class Matriline(db.Model):
    __tablename__ = 'matriline'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode(64))
    calls = db.relationship('Call', backref='matriline', lazy='select')
    pod_id = db.Column(db.Integer, db.ForeignKey('pod.id'))

    def __unicode__(self):
        return self.name

    def __str__(self):
        return self.name


class Pod(db.Model):
    __tablename__ = 'pod'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode(64))
    matrilines = db.relationship('Matriline', backref='pod', lazy='select')
    clan_id = db.Column(db.Integer, db.ForeignKey('clan.id'))

    def __unicode__(self):
        return self.name
    def __str__(self):
        return self.name


class Clan(db.Model):
    __tablename__ = 'clan'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode(64))
    pods = db.relationship('Pod', backref='clan', lazy='select')

    def __unicode__(self):
        return self.name

【问题讨论】:

  • @user2990084:从 WTForms 的角度来看,很明显我们应该将默认值传递给构造函数。使用 flask_admin 时,这有时不是一个选项,因为表单是预先生成并缓存的。

标签: flask flask-admin


【解决方案1】:

我通过process_data解决了这个问题

def on_form_prefill(self, form, id):
    form.clan.choices = [(1, "first"), (2, "second")]
    form.clan.process_data(2)

希望对你有帮助

【讨论】:

    【解决方案2】:

    我有一个非常相似的问题,并通过仅重新处理更改的字段使其工作。我还需要再次传入当前设置的值(否则它会始终设置为默认值):

    from wtforms.utils import unset_value
    
    class CustomView:
        def on_form_prefill(self, form, id):
            form.clan.choices = [(1, "first"),(2,"second")]
            form.clan.default = 2
            form.clan.process(None, form.clan.data or unset_value)
    

    注意:on_form_prefill 仅在 edit_view 中调用,而不在 create_view 中调用,这仅适用于现有实例。

    【讨论】:

    • 谢谢你。这解决了我覆盖 edit_form 以使用自定义表单的问题。
    猜你喜欢
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 2020-01-10
    • 2017-12-08
    相关资源
    最近更新 更多