Ryan Oh
Ryan Oh

Reputation: 657

Can I dynamically place items in two-column template in Django?

The title might not be so clear, so let me elaborate more. I have a two-column template, and want to load some number of items in them. It would look like this:

{{item1}} | {{item2}}
{{item3}} | {{item4}}
{{item5}} | {{item6}}
{{item7}} | {{item8}}
...

And this is the farthest I've got in my template :

{% for a in answers %}
<div class="row justify-content-center">
    <div class="col-6 text-center">
        <div class="row justify-content-center">
            <div class="col">
                <div class="answers">{{a.title}}</div>                
            </div>
        </div>
    </div>
    <div class="col-6 text-center">
        <div class="row justify-content-center">
            <div class="col">
                <div class="answers">{{a.title}}</div>                
            </div>
        </div>
    </div>
</div>
{% endfor %}

Apparently, it doesn't load item as I want to. How do I make this possible? Any help is very much appreciated! :)

+Some other codes for further info:
views.py

def qandaSquare(request, pk):
    answers = Answer.objects.filter(authuser=request.user.id, question_number=pk)
    
    context = {
        'answers' : answers,
    }
    return render(request, 'main/square.html', context)

Upvotes: 0

Views: 175

Answers (1)

Biplove Lamichhane
Biplove Lamichhane

Reputation: 4095

Try:

<div class="row justify-content-center">
{% for a in answers %}
    <div class="col-6 text-center">
        <div class="row justify-content-center">
            <div class="col">
                <div class="answers">{{a.title}}</div>                
            </div>
        </div>
    </div>
    {% if forloop.counter|divisibleby:2 %}
</div>
<div class="row justify-content-center">
    {% endif %}
{% endfor %}
</div>

Refs: divisible_by | forloopcounter

Upvotes: 2

Related Questions