Flask Admin Dashboard Summary
1.0.0
该项目是为了回答这个问题而创建的 - Flask Admin Models - Summary row。该问题引用了之前的 SO 问题,如何为 Flask-Admin 添加摘要行?。
该项目是 Flask-Admin-Dashboard 的克隆,带有额外的视图(项目),显示如何将摘要行添加到 Flask-Admin 列表视图。
该项目与原来的项目不同:
create-database
初始化的该项目附带一个预初始化的数据库( sample_db.sqlite
)。要从 CLI 创建新数据库,请在项目的根目录中运行:
> flask create-database
在 CLI 中,在项目的根目录中运行:
> flask run
* Serving Flask app "app/__init__.py"
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
要显示汇总表,视图需要:
templates/admin/model/summary_list.html
是 list.html 的直接副本
请注意文件名summary_list.html
,因为它在视图定义的render
方法中使用。
以下 html 块已插入到第 163 行:
{# This adds the summary data #}
{% for row in summary_data %}
<tr>
{% if actions %}
<td>
{# leave this empty #}
</td>
{% endif %}
{# This is the summary line title and goes in the action column, note that the action may not be visible!!! #}
{% if admin_view.column_display_actions %}
<td><strong>{{ row['title'] or ''}}</strong></td>
{% endif %}
{# This is the summary line data and goes in the individual columns #}
{% for c, name in list_columns %}
<td class="col-{{c}}">
<strong>{{ row[c] or ''}}</strong>
</td>
{% endfor %}
</tr>
{% endfor %}
views.py
从第 60 行开始。
第 61 行,定义要使用的模板:
# don't call the custom page list.html as you'll get a recursive call
list_template = 'admin/model/summary_list.html'
第 75 行,重写视图的render(self, template, **kwargs)
方法:
def render(self, template, **kwargs):
# we are only interested in the summary_list page
if template == 'admin/model/summary_list.html':
# append a summary_data dictionary into kwargs
# The title attribute value appears in the actions column
# all other attributes correspond to their respective Flask-Admin 'column_list' definition
_current_page = kwargs['page']
kwargs['summary_data'] = [
{'title': 'Page Total', 'name': None, 'cost': self.page_cost(_current_page)},
{'title': 'Grand Total', 'name': None, 'cost': self.total_cost()},
]
return super(ProjectView, self).render(template, **kwargs)
请注意模板上的条件检查,因为我们不关心编辑/创建渲染以及将summary_data
字典注入到方法的**kwargs
参数中。
请注意第 66 行和第 71 行提供实际汇总数据的辅助方法,这些方法需要根据需要进行调整:
def page_cost(self, current_page):
# this should take into account any filters/search inplace
_query = self.session.query(Project).limit(self.page_size).offset(current_page * self.page_size)
return sum([p.cost for p in _query])
def total_cost(self):
# this should take into account any filters/search inplace
return self.session.query(func.sum(Project.cost)).scalar()