I have two admin panels both behaves differently from two different flask admin instances. For second admin panel, I'm trying to restrict the selectable data. So for example, if I have User and Role, in role edit form, I can select all users that exists in DB by default. I want to override this query to say only show data that meets this criteria so that users that uses second admin panel can only select/edit from given data.
I've tried several available solutions but nothing seems to work, rather the form itself comes up correct but the data is not being inserted.
Below are my code snippet
def filtering_function():
return User.query.join(roles_users).join(Role).filter(User.company == current_user.company)
class CustomModelForm(FlaskForm):
Users = QuerySelectField(query_factory=filtering_function)
class SiteRoleView(Accessibility):
def edit_form(self, obj):
return CustomModelForm(obj=obj)
def get_query(self):
return self.session.query(self.model).join(roles_users).join(User).filter(User.company == current_user.company)
The get_query method from above brings out filtered query for list view in admin panel, however, it does not affect the data in edit form view and overriding edit_form method like above does not apply the changes into the DB.
Accessibility is the class that inherits sqla.ModelView
Thanks
Ok I found a solution.
Based on How can I filter a column in the edit form with Flask-Admin ModelView?, the answer by Liu.
you don't need to override edit_form, instead all you have to do is apply different query filter to 'roles' field by assigning form_args into your specific view.
Below is the snipper
def filtering_function():
return Role.query.join(roles_users).join(User).filter(User.company == current_user.company)
class SiteUserView:
form_args = dict(
roles = dict(label='Roles', query_factory=filtering_function)
)