How can I get a random value of a list of objects using custom filters?

104 views Asked by At

I'm trying to get a single random object in a list of objects directly on my template.

Here is an example of what I am trying to do :

views.py goes like this : Font.objects.all()

template file :

{% for f in Fo.checkbox.all %}       #f|random_choice doesn't work here.
    <p>{{ f.font_name|random_choice }}</p>     #gives me a single random character of each object.
{% endfor %}

the example above gives me a single random character of each object in list, but I'm trying to get a random object in the list of object.

here is the templatetag file :

@register.filter(name='random_choice')
def random_choice(l):
    return random.choice(list(l))

How can I do it ?

1

There are 1 answers

3
Joran Beasley On BEST ANSWER

its already built in https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#random

{{ my_list | random }}

if this was for an interview and you gave any other answer than this one ... I hate to tell ya but you probably did not give the answer they were looking for...

{{ Fo.checkbox.all | random }}  {# print one random value from Fo.checkbox.all #}