9

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.

Darwin Tech
  • 18,449
  • 38
  • 112
  • 187
  • 1
    There isn't such a tag, but you can quite easily roll your own tag/filter. You can use `random.shuffle()` to do the shuffling, but do note that this does the shuffling in-place. – Shawn Chin Aug 23 '11 at 14:35

3 Answers3

15

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>
christophe31
  • 6,359
  • 4
  • 34
  • 46
2

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[:]])
djangouser
  • 111
  • 1
  • 4
  • 1
    While I enjoy your attempt at simplicity here, it should be noted that random.shuffle only returns None and only alters the mutable list passed into it. Therefore, you need to copy the list beforehand, like @christophe31 did. def shuffle(arg): tmp = [i for i in arg] random.shuffle(tmp) return tmp – ryanshow Jan 18 '12 at 20:08
  • or we can simply replace `args[:]` by `list(args)` which would fix `Queryset` cases and avoid the assignation error. – christophe31 Feb 18 '14 at 13:41
0

'QuerySet' object does not support item assignment

Anish Menon
  • 789
  • 11
  • 26