gpt4 book ai didi

python - 如何在模板 Django python 中生成随机数?

转载 作者:搜寻专家 更新时间:2023-10-31 22:25:59 26 4
gpt4 key购买 nike

好的,所以我正在尝试使用 Django/Python 制作一个随机数生成器网页。我需要完成的是在我的 HTML 模板文件中以某种方式使用 python 代码,但我不知道如何做到这一点。

<h1 style="font-size:50px;line-height:20px;color:rgb(145,0,0);font-    family: Arial Black, Gadget, sans-serif"></h1>
<h2 style="line-height:10px;color:rgb(140,140,140)"></h2>
<h3 style="font-size:40px;line-height:10px;font-family: Arial Black, Gadget, sans-serif"></h3>
<body style="background-color:rgb(255,239,154)"></body>
<!--Style placeholders-->


<h1 style="text-align:center;position:relative;top:20px">
Test Site
</h1>

<!--Reroll icon-->
<h1 style="text-align:center;position:relative;top:20px">
<input type='image' style='width:60px;height:56px;' src='../../static/polls/dice.png' alt='Re-roll'
onclick='location.reload();' value='Roll' /></h1>

最佳答案

没有内置的方法可以做到这一点。如果您只需要一个随机值,一次,并且您不想从 View 函数中传递它 - 我想自定义模板标签就是这种方式。

在任何适当的应用程序中,创建一个文件 templatetags/random_numbers.py(如果您没有任何其他自定义模板标签,则创建一个空的 templatetags/__init__.py ) 包含以下内容:

import random
from django import template

register = template.Library()

@register.simple_tag
def random_int(a, b=None):
if b is None:
a, b = 0, a
return random.randint(a, b)

然后,在您的模板中像这样使用它:

{% load random_numbers %}

<p>A random value, 1 ≤ {% random_int 1 10 %} ≤ 10.</p>

关于自定义标签的更多文档:https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/

关于python - 如何在模板 Django python 中生成随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36744109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com