I'm trying to pick up 3 random numbers out of a list of 20 numbers.
In views.py, I've defined this variable:
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
In my template index.html:
{{ nums|random }} - {{ nums|random }} - {{ nums|random }}
I want to get 3 different numbers, but I don't know which filter/tag to apply.
I've tried if/else statements, for loops, (if there's a duplicate I want a redraw) but i'm not satisfied with the results and I'm pretty sure there's a simple filter to do that.
I don't think there's a reasonable way to do this with the built in filters. I'd just pick the numbers in the view and pass that in to the context.
If your rendering is consistent and you want to do this a lot of places you could write a custom template tag, eg:
import random
from django import template
register = template.Library()
@register.simple_tag
def random_sample(population, k):
return ' - '.join(str(choice) for choice in random.sample(population, k))
Then {% random_sample nums 3 %} in your template.
But I think doing it in the view is simpler.
You could create your templatetag with this functionalitiy to solve your problem.
yourapp/templatetags/custom_choice_tags.py
from django import template
import random
register = template.Library()
@register.assignment_tag
def get_three_unique_random_values_from_list(value_list):
random_choices = random.sample(value_list, 3)
selected_choices = {
'first_choice': random_choices[0],
'second_choice': random_choices[1],
'third_choice': random_choices[2],
}
return selected_choices
and then in your template.html:
{% load custom_choice_tags %}
{% get_three_unique_random_values_from_list random_list as random_choices %}
{{ random_choices }}
the variable random_list would be passed from your view into the template context in this example.