Doubt when ranking using Jango!

Asked

Viewed 174 times

1

I’m making a site of a game using Jango and I want to make a ranking based on the score of all users! For now it’s like this:

py views.:

def index(request):
    perfis = Perfil.objects.all().order_by('-pontuacao_ultima')
    return render(request, 'index.html', {'perfis' : perfis})

index.html:

{% for perfis in perfis %}
    <tr>
        <td>1</td>
        <td>{{ perfis.nome }}</td>
        <td>{{ perfis.pontuacao_ultima }} pontos</td>
    </tr>
{% endfor %}

In the case it is already ordering, but I am doubtful what to do to the position number vary according to the actual position of the player (first, second, etc.). For now it is showing only the 1 (manually put in html).

2 answers

1


Use the tag forloop.counter:

{% for perfil in perfis %}
    <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ perfil.nome }}</td>
        <td>{{ perfil.pontuacao_ultima }} pontos</td>
    </tr>
{% endfor %}

There are other tags with different functions, such as starting from scratch forloop.counter0, check if it is the first loop loop loop {% if forloop.first %}, etc..

More details can be seen on documentation.

1

Good evening, I believe an "enumerate" can help you, and according to Django’s documentation, you would have one available through the variable {{ forloop.counter }} inside your block for, That’s because you want an initial ranking of 1, if not, if you wanted the real Index of the object inside the list, you could use {{ forloop.counter0 }}.

References: - https://stackoverflow.com/questions/5013367/how-to-run-this-code-in-django-template

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.