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"]))
current_user
is not available then. It's only available inis_accessible()
and_handle_view()
(like they do in the example). But settingself.form_create_rules
in those methods has no effect :( . – Slashself.form_create_rules
and regenerate forms, but it is discouraged - forms are cached for performance reasons. Instead, you can overridecreate_form
andedit_form
and return different forms (or remove fields from existing form). See here: github.com/flask-admin/flask-admin/blob/master/flask_admin/… – Moire