Lewis137
Lewis137

Reputation: 27

Django Randomly Select List Item to Display In Template

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

Answers (2)

D Malan
D Malan

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

Safwan Samsudeen
Safwan Samsudeen

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

Related Questions