Search code examples
flaskflask-admin

on_form_prefill delete all fields values if it executes form.process


I want to override the form of the Matriline model shown below.

First I add an extra field clan, and in on_form_prefill I reset this field's choices and default (just testing).

Without calling form.process the choices are set to my new options, but the default option is not selected.

If calling form.process the choices are set to my new options and the default option is selected, but all the other fields are deleted.

Anybody can help?

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

Solution

  • I solve this problem by process_data

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

    I hope this can help you