several_random template filter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import random as random_module

def several_random(value, arg=1):
    "Returns one or more random item(s) from the list"
    try:
        arg = int(arg)
    except ValueError:
        return value
    if arg == 1:    
        return random_module.choice(value)
    elif len(value) > arg:  # Only pick if we are asked for fewer items than we are given
        return random_module.sample(value, arg)
    else:   # Number requested is equal to or greater than the number we have, return them all in random order
        new_list = list(value)
        random_module.shuffle(new_list)
        return new_list

More like this

  1. Repeat Tag by daniellindsley 4 years ago
  2. Pagination/Filtering Alphabetically by zain 4 years, 2 months ago
  3. in_group template filter by whiteinge 4 years, 10 months ago
  4. Template filter to get a list element by its index by abidibo 1 year ago
  5. django-mptt enabled FilteredSelectMultiple m2m widget by anentropic 3 years, 6 months ago

Comments

(Forgotten your password?)