所以我创建了一个基本的Flask-User应用程序,其中包含多个角色和数据结构:
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
active = db.Column('is_active', db.Boolean(), nullable=False, server_default='0')
first_name = db.Column(db.String(50), nullable=False, default='')
last_name = db.Column(db.String(50), nullable=False, default='')
email = db.Column(db.String(255), nullable=False, unique=True)
confirmed_at = db.Column(db.DateTime())
# Relationships
user_auth = db.relationship('UserAuth', uselist=False)
roles = db.relationship('Role', secondary='user_roles',
backref=db.backref('users', lazy='dynamic'))
def is_active(self):
return self.active
class UserAuth(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE'))
# User authentication information
username = db.Column(db.String(50), nullable=False, unique=True)
password = db.Column(db.String(255), nullable=False, default='')
# Relationships
user = db.relationship('User', uselist=False)
def hash_password(self, password):
self.password_hash = pwd_context.encrypt(password)
def verify_password(self, password):
return pwd_context.verify(password, self.password_hash)
class Role(db.Model):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(50), unique=True)
class UserRoles(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE'))
role_id = db.Column(db.Integer(), db.ForeignKey('role.id', ondelete='CASCADE'))
我尝试在Flask-Admin中显示它:
class AdminView(ModelView):
def is_accessible(self):
access = current_user.is_authenticated and current_user.has_role('admin')
return access
admin = Admin(app, name='My Admin', template_mode='bootstrap3')
admin.add_view(AdminView(User, db.session))
admin.add_view(AdminView(UserAuth, db.session))
admin.add_view(AdminView(Role, db.session))
admin.add_view(AdminView(UserRoles, db.session))
如何在编辑用户时查看并能够编辑用户角色?
答案 0 :(得分:1)
您尚未为var()
类的实例定义合适的字符串表示形式。一个合适的例子是:
UserAuth
这需要为您的所有模型完成。