Darwin Tech
Darwin Tech

Reputation: 18929

django shuffle in templates

as part of a keyword cloud function in Django, I am trying to output a list of strings. Is there a filter for templates which allows you to shuffle items in a list? I thought this would be straightforward, but I can't find any applicable filters in the official docs.

Upvotes: 9

Views: 4992

Answers (3)

christophe31
christophe31

Reputation: 6467

it's straightforward to make yours.

# app/templatetags/shuffle.py
import random
from django import template
register = template.Library()

@register.filter
def shuffle(arg):
    tmp = list(arg)[:]
    random.shuffle(tmp)
    return tmp

and then in your template:

{% load shuffle %}
<ul>
{% for item in list|shuffle %}
    <li>{{ item }}</li>
{% endfor %}
</ul>

Upvotes: 15

Anish Menon
Anish Menon

Reputation: 809

'QuerySet' object does not support item assignment

Upvotes: 0

djangouser
djangouser

Reputation: 111

Just to add, if it's a query set, it'll throw an error since object list can't be assigned. Here is a fix fr christophe31 code:

import random
from django import template
register = template.Library()

@register.filter
def shuffle(arg):
    return random.shuffle([i for i in arg[:]])

Upvotes: 2

Related Questions