alex
alex

Reputation: 2541

Django can't get counted votes in template

I'm trying to count and show how many votes every user gave. When i'm doing it in python console it shows me, but i can't get it from template.

In console:

from football_app.models import Score
from football_app.models import CustomUser

for user in CustomUser.objects.all():
    x = Score.objects.filter(granted_to=user).count()
    print(x)

0
1
1
1
1
1

0 because the request.user is not allowed to give himself a vote.

In views:

def test(request):
    data = dict()
    User = get_user_model()
    for user in User.objects.all():
        count_grades = Score.objects.filter(granted_to=user).count()
        data['count_grades'] = str(count_grades)
    return render(request, 'test.html', data)

test.html

{% for number_of_votes in count_grades %}
    {{ number_of_votes }}
{% endfor %}

or even

{{ count_grades }}

It shows me just 1, that's all. Why isn't it showing for each user?

Upvotes: 1

Views: 76

Answers (1)

Shreyash S Sarnayak
Shreyash S Sarnayak

Reputation: 2335

You need to create a list and append grade count to it to display

data['count_grades'] = []
for user in User.objects.all():
    count_grades = Score.objects.filter(granted_to=user).count()
    data['count_grades'].append(str(count_grades))

Doing data['count_grades'] = str(count_grades) will overwrite the previous value. Because of this the last value 1 was getting displayed.

Upvotes: 1

Related Questions