Flask-admin; To add custom logic during row insertion

爱⌒轻易说出口 提交于 2020-01-25 21:13:11

问题


I'm new to the flask-admin library so please forgive me if this is trivial. When I click 'Save' to create a new row for a model, I also want to do some custom things. In my case, I'll create a table dynamically whose name is the string entered in the form. This will be in addition to what flask-admin does for me i.e. add a new row to the model table. So where will I put the custom logic to do what I want to do? I saw this post on so: Customize (override) Flask-Admin's Submit method from edit view with Joe's answer about overriding on_model_change but I'll like some more explanation. From the docs, it says that on_model_change is called from update_model and create_model. When I click on the source link to the right, I get to: http://flask-admin.readthedocs.org/en/latest/_modules/flask_admin/model/base/#BaseModelView.create_model . It doesn't show the code. So I don't know how it is implemented. Can someone please illustrate what I'm trying to in a simple sample code? Thanks.


回答1:


The right way of doing this (as you have mentioned) is through after_model_change function. Quoting Flask-Admin source code

def after_model_change(self, form, model, is_created):
    """
        Perform some actions after a model was created or updated and
        committed to the database.

        Called from create_model after successful database commit.

        By default does nothing.

        :param form:
            Form used to create/update model
        :param model:
            Model that was created/updated
        :param is_created:
            True if model was created, False if model was updated
    """
    pass

So basically, in your case, you need to perform the table creation inside this function on your model. Namely

class MyModelView(BaseModelView):
     column_list = ('fieldX', 'fieldY')

     def after_model_change(self, form, model, is_created):
         tablename = form.tablename
         if is_created: # create the table just once
             perform_dynamic_table_creation(conn,tablename)


来源:https://stackoverflow.com/questions/32708006/flask-admin-to-add-custom-logic-during-row-insertion

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