python - 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?
解决方案
Django 有一个模板过滤器:random
. 您可以在列表中使用它,例如:
{{ list_of_values|random }}
但是,如果您希望能够缓存页面,则可能需要考虑像您提到的基于 JavaScript 的解决方案。
推荐阅读
- vb.net - 获取当前 user.config 路径 (Visual Basic)
- reactjs - React Symfony 5.0.7 在标题中没有看到 JWT
- c# - 为什么我的函数没有在几秒钟内返回正确的值?
- python-3.x - FastText 0.9.2 - 召回率是“南”,但精度是一个数字
- javascript - 如何检测跨度是否已调整大小?
- html - 我尝试将我的 CSS 链接到我的 HTML,但它似乎不起作用
- node.js - 回调中的对象
- python - 使用 piptools 时如何在生成的 requirements.txt 中不打印索引 url
- c# - 文本框由于其保护级别而无法访问
- powershell - Powershell 和 Unicode 支持