Custom form of the admin flag with some field selection options defined in accordance with another selection field

I am trying to use Flask-Admin to create a create / edit form for the Matriline model shown below. This model has a name field field and a pod_id field with a foreign key constraint for another Pod model, which itself has a foreign key field for a Clan .

The default form created by Flask-Admin shows the name field and the select field for Pod instances, but I would like to add a Clan field that will reset the Pod list according to the selected Clan instance.

To add a Clan field, I override the default ModelView for Matriline by default and add an additional Clan selection field with all clan instances, as shown in the MatrilineView view below.

Now I need to add some Ajax code to the rendered form in the reset list of modules every time a new clan is selected.

Should I completely replace the default form with a custom one, including Ajax code? Or is there an easier way with Flask-Admin?

<b>models.py</b> ... class Matriline(db.Model): __tablename__ = 'matriline' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Unicode(64)) pod_id = db.Column(db.Integer, db.ForeignKey('pod.id')) def __unicode__(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 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 ... <b>views.py</b> from flask_admin.contrib import sqla from wtforms import SelectField from orcall import models class MatrilineView(sqla.ModelView): column_hide_backrefs = False form_extra_fields = { 'clan': SelectField('Clan', choices=[ (c.id, c.name) for c in models.Clan.query.all()]) } column_list = ('name', 'pod', 'clan') ... 
+5
source share
1 answer

You need to use QuerySelectField . For instance:

 from flask.ext.admin.form import Select2Widget class MatrilineView(sqla.ModelView): column_hide_backrefs = False form_extra_fields = { 'clan': sqla.fields.QuerySelectField( label='Clan', query_factory=lambda: Clan.query.all, widget=Select2Widget() ) } column_list = ('name', 'pod', 'clan') 
+4
source

All Articles