【问题标题】:Flask Admin Models - Summary rowFlask Admin Models - 摘要行
【发布时间】:2018-10-27 00:17:27
【问题描述】:

我正在使用 Flask Admin (https://github.com/jonalxh/Flask-Admin-Dashboard),但我有疑问。

假设我有一个模型:

产品

序列号

价格

我正在寻找一种方法来显示一个新行,以显示库存产品的总价格。

有人能指出正确的方向吗?

谢谢。

我已经对此进行了研究,但是当我显示自定义视图时,我无法像在“标准”模型视图上那样执行 CRUD 操作:How do you add a summary row for Flask-Admin?

P.S:我正在学习 python,所以如果这是我在浪费你时间的基本问题,请原谅

【问题讨论】:

标签: python flask-sqlalchemy flask-admin


【解决方案1】:

引用question 的答案中概述的方法也可以与 Flask-Admin-Dashboard 一起使用。

我在 Github 上创建了一个示例项目Flask-Admin-Dashboard-Summary

以下是基本概念。

要显示汇总表,视图需要:

  • 将汇总值注入视图
  • 定义要使用的 Jinja 模板并适当修改它以使用注入的汇总值

设置 Jinja 模板

templates/admin/model/summary_list.htmllist.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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-11
    • 2022-01-18
    • 2012-08-02
    • 2016-10-21
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 2021-03-11
    相关资源
    最近更新 更多