我是burn-admin图书馆的新手,所以请原谅我,如果这是微不足道的。当我点击'保存'为模型创建一个新行,我也想做一些自定义的事情。在我的例子中,我将动态创建一个表,其名称是在表单中输入的字符串。这将是flask-admin为我做的补充,即向模型表添加新行。那么我将把自定义逻辑放在哪里做我想做的事情?我看到这篇文章是这样的:Customize (override) Flask-Admin's Submit method from edit view以及Joe关于覆盖on_model_change的答案,但我想要更多解释。从文档中可以看出,on_model_change是从update_model和create_model调用的。当我点击右边的源链接时,我会:http://flask-admin.readthedocs.org/en/latest/_modules/flask_admin/model/base/#BaseModelView.create_model。它没有显示代码。所以我不知道它是如何实现的。 有人可以在一个简单的示例代码中说明我想要尝试的内容吗?感谢。
答案 0 :(得分:2)
正确的做法(正如您所提到的)是通过after_model_change
功能。引用Flask-Admin源代码
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
基本上,在您的情况下,您需要在模型上的此函数内执行表创建。即
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)