Метод, описанный в ответе на указанный вопрос , также можно настроить для работы с Flask-Admin-Dashboard.
Я создал пример проекта Flask-Admin-Dashboard-Summary на Github.
![Summary Rows for Project View](https://i.stack.imgur.com/nQ2TX.jpg)
Ниже приведены основные понятия.
Чтобы отобразить сводную таблицу, представление должно:
- вводить итоговые значения в представление
- определить, какой шаблон Jinja использовать, и соответствующим образом изменить его, чтобы использовать введенные итоговые значения
Настройка шаблона Jinja
templates/admin/model/summary_list.html
- это прямая копия list.html из папки шаблонов Flask-Admin Bootstrap 3.
Обратите внимание на имя файла, summary_list.html
, так как оно используется в методе определения вида render
.
В строке 163 вставлен следующий блок html:
{# 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 %}
Настройка вида
Строка 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)
Обратите внимание на вспомогательные методы для предоставления фактических сводных данных в строках 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()