Reputation: 27
I have a list of strings in a .py file located in the same dir as my working app. I want to display a randomly selected item from the list and have it display in the template of my app. On each refresh of the page i want the random selection to change. I can't work out how this is possible at the moment.
I'm thinking two things: run a random selection within the .py that has my list; or bring the entire list into the template and then use JS(?) to randomly select an item.
Any advice?
Upvotes: 0
Views: 990
Reputation: 11434
Django has a template filter for that: random
. You can use it on lists, e.g.:
{{ list_of_values|random }}
If you ever want to be able to cache the page though, you might want to consider a JavaScript-based solution like you mentioned.
Upvotes: 3
Reputation: 1707
Use the choices
function from the random
module.
views.py
import random
from somewhere.filename import strings
def index(request):
return render('template.html', {'list_item', random.choice(strings)})
Upvotes: 1