Doubt when doing a ranking using django!

1

I'm making a game site using django and I want to do a ranking based on the score of all users! For now it looks like this:

views.py :

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 case he is already ordering, however I am doubtful what to do for the position number to vary according to the actual position of the player (first, second, etc.). For now it is showing only the 1 (I put it manually in the html).

    
asked by anonymous 09.02.2018 / 00:38

2 answers

1

Use the forloop.counter tag:

{% 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 start counting from zero forloop.counter0 , check if it's the first loop of the {% if forloop.first %} loop, etc.

More details can be found at documentation .

    
09.02.2018 / 00:57
1

Good evening, I believe that an "enumerate" can help you, and according to the Django documentation, you would have one available through the variable {{ forloop.counter }} within your for block, that's why you want a ranking starting from 1 , if not, if you wanted the actual Index object within the list, you could use {{forloop.counter0}}.

References: - link

I hope I have helped!

    
09.02.2018 / 00:59