'How to get the sum of values in Django template for loop or how i can implement the same in Django view

this is my template

<div class="row m-5 p-3 border bg-white">
    <table class="table ">
        <tr>
            <th>Project Name</th>
            <th>Total Partnership</th>
        </tr>
        {% for pages in page %}
        <tr>
            <td>{{pages.name}}</td>
            
            <td>
                {% for i in pages.partnership_set.all %}
                {{i.partnership}}%
                
                {% endfor%}
            </td> 
        </tr>
        {% endfor %}
    </table>
   
</div>

my view is:

def fnviewproject(request):
projects=project.objects.all()
paginator=Paginator(projects,3)
page_num=request.GET.get('page')
page_obj=paginator.get_page(page_num)
context={'page':page_obj}
return render(request,"viewproject.html",context)

my output is: |project Name | Total Partnership | |-------------|-------------------| |project 1. | 100%. | |project 2. | 20% 30% 40%. | |project 3. | 45% 30%. |

i just wanted this total partnerships to be added and displayed.how can i do it either in template or else in view?



Solution 1:[1]

You can create a custom templatetag if you want the processing to be done in the template.

project_dir/app_name/templatetags/sometag.py

from django import template

register = template.Library() 

@register.filter
def total_percentage(value):
    temp_val = value.split(' ')
    percentage = 0
    
    for val in temp_val:
        percentage += int(val[:-1])

    return str(percentage) + '%'

Then call it in your template like this:

{% load sometag %}
{% total_percentage i.partnership %}

Solution 2:[2]

The designers of Django took the view that remplates are for data presentation. Business logic should be implemented in Python code. "Opinionated". So you can't easily and naturally create totals in a template, only display them.

You don't show your models, but if I guess right you want each pages to display the count of objects in partnership_set? If so, you can get that direct from the database with a queryset annotation (like cheat sheet example 6)

project = Project.objects.all().annotate(
    total_partnerships = Count('partnership')
)

Then in your template

{{ pages.total_partnerships }}

For something more complex you would write a Python function to calculate it, and either call it and pass the result through your context to the template, or attach it to an appropriate model as a property:

class Something (models.Model):
    ...

    @property
    def foo_value( self):
       # calculate value based on model instance represented by self
       return value

in your template

{{ something.foo_value}}

By the way, your code will be improved if you stick to Django conventions. Model classes start with capital letters Project, not project. An instance of the class doesn't, so you can naturally write project = Project( field=value, ...) or projects = Project.objects.all(). Also try to use meaningful variable names. page isn't obviously so.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Naeem Khan
Solution 2