mardi 25 août 2015

django for loop random order determine

I want to have a tag list of 10 main tags but displayed in random order because the font weight will determine their weight.

first i order objects and get 10 tags, than I use shuffle to randomise the order. So far it works. My issue now is to use {{forloop.counter0}} in template which outputs below code in random order:

    <tr>
        <td class="tag-0">Tag3</td>
    </tr>
    <tr>
        <td class="tag-1">Tag1</td>
    </tr>
    <tr>
        <td class="tag-2">Tag2</td>
    </tr>

Instead I want it to be like this:

<tr>
    <td class="tag-0">Tag1</td>
</tr>
<tr>
    <td class="tag-1">Tag2</td>
</tr>
<tr>
    <td class="tag-2">Tag3</td>
</tr>

template:

{% for t in tags %}
    <tr>
        <td class="tag-{{forloop.counter0}}">{{t.title}}</td>
    </tr>
{% endfor %}

in views:

tags = list(Model.objects.order_by('title')[:10])
random.shuffle(tags)




Aucun commentaire:

Enregistrer un commentaire