Hiding fields in Flask-Admin depending on logged in user?

南楼画角 提交于 2019-12-01 01:21:16
pjcunningham

One way of achieving this is to create multiple view classes and register these view classes against their appropriate roles. See this answer on how to register roles to views. Using view inheritance you can keep common functionality in the "base" class.

For example, suppose we have a user table that implements the Flask-Security mixin and we want the role "admin" to be able to read/set the active field and anyone with the role "user" not to see this field. The class AdminView is defined in the referenced answer.

class AdminUserView(AdminView):

    column_list = ['first_name', 'last_name', 'email', 'roles', 'active']

    form_columns = ['first_name', 'last_name', 'email', 'active', 'roles']

    # Other common functionality here

class UserView(AdminUserView): 

    # Just redefine the columns that can be seen/edited

    column_list = ['first_name', 'last_name', 'email', 'roles']

    form_columns = ['first_name', 'last_name', 'email', 'roles']

# register your views and remember to set a unique endpoint as we are using the same model in multiple views

admin.add_view(AdminUserView(model=User, session=db.session, category="Accounts", name="Users", endpoint="users_admin", roles_accepted=["admin"]))
admin.add_view(UserView(model=User, session=db.session, category="Accounts", name="Users", endpoint="users_user", roles_accepted=["user"]))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!