首页 > 解决方案 > 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?

标签: pythondjangolist

解决方案


Django 有一个模板过滤器:random. 您可以在列表中使用它,例如:

{{ list_of_values|random }}

但是,如果您希望能够缓存页面,则可能需要考虑像您提到的基于 JavaScript 的解决方案。


推荐阅读