JustMe
JustMe

Reputation: 327

How to make a div appear only once in a loop?

I've created a model Team in models.py in Django for which I've created in views.py the following code:

def team(request):
    obj = Team.objects.all().order_by('?')
    context = {'team': obj}
    return render(request, 'website/team.html', context)

In HTML I've created a team loop which is displaying all the team members available.

    {% for team in team %}
        <div class="member animated delay1" data-effect="fadeInUp">
            <div class="team-image">
                 <div class="teamDescription">
                     <p>{{ team.description }}</p>
                 </div>
                 <img src="{{ team.picture.url }}">
                 </div>
            <div class="blueLine"></div>
            <div class="team-name-function animated delay1" data-effect="fadeInUp">
                <h5>{{ team.name }} {{ team.surname }}</h5>
                    <p>{{ team.title }}</p>
            </div>
        </div>
   {% endfor %}

In this loop, I need to make available one div with the numbers of team members, which has to appear only once and randomly as team members. Currently I have <div class="number">{{ team.count }}</div> outside the loop.

How do I integrate the members counting in the loop and make it appear only once?

Thank you in advance for any solution!

Upvotes: 1

Views: 225

Answers (1)

Amin Mir
Amin Mir

Reputation: 642

In the view use teams instead of team: context = {'teams': obj}

create a random number between 1 and teams length in view

import random
....
random_number = random.randint(a,len(teams)) # insert it after teams
...
context = {
    'team': obj,
    'random' : random_number,
}

then in the template use {% for team in teams %}

and if you want to show teams length just one time it's possible to use

{% if forloop.counter==random %}
     <div class="number">{{ teams.count }}</div>
{% endif %}

Upvotes: 2

Related Questions