Reputation: 756
I used the classes below, allowing users to edit their own profile after registering and it works well. I achieve this using get_query
and get_count_query
.
However, if the current user is administrator, how can I customize it to let him/her view all users' profiles instead of just his/her own profile? Thanks in advance.
from flask_admin.contrib.sqla.view import ModelView, func
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(255))
last_name = db.Column(db.String(255))
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
def __str__(self):
return self.email
class UserView(ModelView):
"""
Restrict only the current user can see his/her own profile
"""
def get_query(self):
return self.session.query(self.model).filter(self.model.id==current_user.id)
def get_count_query(self):
return self.session.query(func.count('*')).filter(self.model.id==current_user.id)
Upvotes: 2
Views: 2935
Reputation: 137
Another option here is to check the user and handle accordingly in y our get_query
or get_count_query
such as:
def get_query(self):
if current_user.username == 'admin':
return self.session.query(self.model)
else:
return self.session.query(self.model).filter(
# your existing filter for user
)
Note: the above uses current_user
from flask_security but can be adapted to other logic easily.
Upvotes: 3
Reputation: 6475
You can define another custom ModelView
for administrator. For example:
class UserViewForAdmin(ModelView):
def is_accessible(self):
return current_user.has_role("admin")
def inaccessible_callback(self, name, **kwargs):
return redirect(url_for("security.login", next=request.url))
pass
admin = Admin(name="Flask-Admin Example")
admin.add_view(UserView(User, db.session, name="Profile")
admin.add_view(UserViewForAdmin(User, db.session, name="UserList", endpoint="users")
The is example assume you use Flask-Security
to do user management.
Upvotes: 4