How can I filter a column in the edit form with Flask-Admin ModelView?

有些话、适合烂在心里 提交于 2019-12-23 01:16:14

问题


I am using a model view with flask-admin and I want to filter a column in the edit/create view. The column/field is a relationship and I only want to show fields that belong to the logged in user i.e. relationship_id == user.id


回答1:


Actually I found a easier way for that as below, seems there's no need to override the edit_form method in ModelView, just pass the filtering function as a named parameter(query_factory) to the form_args, and it works like a charming!.

class CustomModelView(ModelView):
    form_args = dict(
        status = dict(label='Status', query_factory=filtering_function)
    )

def filtering_function():
   return app.db.query(CustomModel).filter_by(field_to_filter=my_criteria)



回答2:


I was able to figure this out. Hope the code below helps. It's working pretty well for me.

Below is a rough idea of the code:

class CustomModelView(ModelView):
    def edit_form(self, obj):
        return CustomModelForm(obj=obj)

def filtering_function():
   return app.db.query(CustomModel).filter_by(field_to_filter=my_criteria)

#from wtforms.form import Form
class CustomModelForm(Form):
    field_to_filter = QuerySelectField(query_factory=filtering_function)


来源:https://stackoverflow.com/questions/29525044/how-can-i-filter-a-column-in-the-edit-form-with-flask-admin-modelview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!