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 ?
its already built in https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#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...