You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask-Admin编辑User模型时出现TypeError错误求助

问题

完成Miguel的Flask Mega教程后,我尝试用Flask-Admin搭配Flask-Login搭建管理仪表板,直接操作SQLite数据库中的模型实体。但编辑User模型时出现错误:

TypeError: BaseModelView.edit_view() got an unexpected keyword argument 'cls'

我的User类代码:

class User(PaginatedAPIMixin, UserMixin, db.Model):
    id: so.Mapped[int] = so.mapped_column(primary_key=True)
    username: so.Mapped[str] = so.mapped_column(sa.String(64), index=True,
                                                unique=True)
    email: so.Mapped[str] = so.mapped_column(sa.String(120), index=True,
                                             unique=True)
    password_hash: so.Mapped[Optional[str]] = so.mapped_column(sa.String(256))
    posts: so.WriteOnlyMapped['Post'] = so.relationship(back_populates='author')
    about_me: so.Mapped[Optional[str]] = so.mapped_column(sa.String(140))
    last_seen : so.Mapped[Optional[datetime]] = so.mapped_column(
        default=lambda: datetime.now(timezone.utc)
    )
    following: so.WriteOnlyMapped['User'] = so.relationship(
        secondary=followers,
        primaryjoin=(followers.c.follower_id == id),
        secondaryjoin=(followers.c.followed_id == id),
        back_populates='followers'
    )
    followers: so.WriteOnlyMapped['User'] = so.relationship(
        secondary=followers,
        primaryjoin=(followers.c.followed_id == id),
        secondaryjoin=(followers.c.follower_id == id),
        back_populates='following'
    )
    tasks: so.WriteOnlyMapped['Task'] = so.relationship(back_populates='user')
    token: so.Mapped[Optional[str]] = so.mapped_column(
        sa.String(32), index=True, unique=True
    )
    token_expiration: so.Mapped[Optional[datetime]]
    is_admin: so.Mapped[Optional[str]] = so.mapped_column(sa.Boolean, default=False)
    
    def __repr__(self):
        return '<User {}>'.format(self.username)

对应的视图代码:

class UserModelView(ModelView):
    def is_accessible(self):
        return current_user.is_authenticated and current_user.is_admin

    def inaccessible_callback(self, name, **kwargs):
        # redirect to login page if user doesn't have access
        return redirect(url_for('auth.login', next=request.url))

奇怪的是编辑、删除Post模型完全正常,请问问题出在哪?

解决方案
  • 核心原因:Flask-Admin与SQLAlchemy 2.0+类型注解兼容性问题:你的User模型使用了SQLAlchemy 2.0的Mapped/WriteOnlyMapped新类型注解,旧版本Flask-Admin对这种定义方式支持不全,编辑时传递了未预期的cls参数引发报错。Post模型未使用这类新注解,所以正常运行。
  • 解决方法1:升级Flask-Admin到最新版本:新版本已适配SQLAlchemy 2.0的类型注解,执行命令:
    pip install --upgrade flask-admin
    
  • 解决方法2:修正User模型的字段定义问题:
    • is_admin字段的类型注解错误:你写了so.Mapped[Optional[str]]但实际是布尔类型,修正为:
      is_admin: so.Mapped[Optional[bool]] = so.mapped_column(sa.Boolean, default=False)
      
    • token_expiration字段缺少列定义,补充完整:
      token_expiration: so.Mapped[Optional[datetime]] = so.mapped_column()
      
  • 解决方法3:显式指定视图的模型类:初始化UserModelView时,确保明确关联模型,比如:
    admin.add_view(UserModelView(User, db.session))
    
    或者在视图类中添加:
    class UserModelView(ModelView):
        __model__ = User
        # 其余代码不变
    

内容的提问来源于stack exchange,提问作者Dream_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 13:34:52