开发者

django shuffle in templates

开发者 https://www.devze.com 2023-03-30 06:47 出处:网络
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 shuff开发者_开发技巧le items in a list? I thought this would

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 shuff开发者_开发技巧le items in a list? I thought this would be straightforward, but I can't find any applicable filters in the official docs.


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>


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[:]])


'QuerySet' object does not support item assignment

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号