如何在Flask Admin的编辑表单中添加额外的字段?

时间:2019-03-06 10:43:08

标签: python flask flask-admin

我想使用Flask Admin在用户编辑表单中添加一个字段项目

为此,我尝试覆盖 edit_form 方法,以将该字段添加为表单的附加属性,但未添加该字段。

我找不到任何有关如何在Flask Admin中向表单添加字段的清晰文档。

有人可以帮忙吗?

class UserAdminView(ModelView):
    column_exclude_list = ['password',]    
    form_widget_args = {
        'password':{
            'disabled': True
        }
    }

    def edit_form(self, obj=None):
    form = super(UserAdminView, self).edit_form(obj)

    form.projects = sqla.fields.QuerySelectMultipleField(
        "Projects",
        query_factory=lambda: db.session.query(Project).join(UserProjectRel) \
        .filter(UserProjectRel.user_id==obj.id),
    )

    return form


class User(db.Model):  
    __tablename__ = 'phaunos_user'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(255), nullable=False)
    is_admin = db.Column(db.Boolean, default=False, nullable=False)
    confirmed_on = db.Column(db.DateTime, nullable=True)


class UserProjectRel(db.Model):
    __tablename__ = 'user_project_rel'
    user_id = db.Column(db.Integer, db.ForeignKey('phaunos_user.id'), primary_key=True)
    project_id = db.Column(db.Integer, db.ForeignKey('project.id'), primary_key=True)
    user_role = db.Column(ENUM(Role), nullable=False)

    user = db.relationship('User', backref=db.backref('user_project_rel', cascade='all'))
    project = db.relationship('Project', backref=db.backref('user_project_rel', cascade='all'))

enter image description here

2 个答案:

答案 0 :(得分:0)

我首先必须重写get_edit_form:

class UserAdminView(ModelView):
    column_exclude_list = ['password',]
    form_excluded_columns = ['annotations', 'user_project_rel']
    form_widget_args = {
        'password':{
            'disabled': True
        }
    }

    def get_edit_form(self):
        form = super(UserAdminView, self).get_edit_form()
        form.projects = sqla.fields.QuerySelectMultipleField("Projects")
        return form

    def edit_form(self, obj=None):
        form = super(UserAdminView, self).edit_form(obj)
        form.projects.query = db.session.query(Project).join(UserProjectRel) \
            .filter(UserProjectRel.user_id==obj.id).all()
        form.projects.data = form.projects.query
        return form

答案 1 :(得分:0)

我认为您错过了BaseModelView类的form_extra_fields属性,因此要添加project输入:

from wtforms.fields import TextField

class UserAdminView(ModelView):
...
    form_extra_fields = {
        'Projects': TextField('Projects')
    }