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()