django - Summing a column after filtering Django 2.1
问题描述
This is my for loop (in my template.html):
{% for item in filter.qs %}
<tr>
<th scope="row">{{ item.id }}</th>
<td>{{ item.nome }}</td>
<td>{{ item.data|date:"d, F" }}</td>
<td>{{ item.tipo_pgto}}</td>
<td>{{ item.mes }}</td>
<td>{{ item.entrada }}</td>
<td>{{ item.valor}}</td>
</tr>
{% endfor %}
The variable {{ item.valor }} holds a decimal number after filtering. How can I sum it and put the result in another part of my HTML? Is the better practice use now JavaScript or there is a way like creating a variable in my view.py and then place it in html?
解决方案
Doing it in JS would be fine, but IMO passing it through the context from the view is better. JS is much harder to do tests for.
If you use Jinja templates (really easy to set up and to use), you could use their filters:
{{ filter.qs | sum(attribute='valor') }}
推荐阅读
- django - 如何在 django 中完全使用 asgi?
- php - PHP:在数组中存储数组似乎是在创建副本
- vba - 单击时生成 MsgBox 的文本框事件
- javascript - jQuery:“data-target”切换功能——只显示一个内容区域
- c++ - 是否可以直接保留并复制到 std::string 中?
- python - 如何获取转发器消息名称 python pytelegrambotapi
- php - Laravel 路由删除父路由
- r - 对 data.frame 值应用计算,存储在新的 data.frame - R
- javascript - 如何将 setTimeout 与 document.querySelectorAll 一起使用?
- python - Pyinstaller:无法执行脚本细胞