问题描述
好的,所以我正在尝试使用Django/Python创建一个随机数生成器网页.我要做的就是以某种方式在我的HTML模板文件中使用python代码,除非我不知道该怎么做.
Okay, so I'm trying to make a random number generator webpage using Django/Python. What I need to accomplish to do that is somehow use python code in my HTML template file, except I can't find out how to do that.
<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>
推荐答案
没有内置的方法可以做到这一点.如果您只需要一个随机值,并且一次又不想从视图函数中传递该值,那么我想是自定义模板标签.
There is no built-in way to do this. If all you need is a random value, once, and you don't want to pass that from a view function - I guess a custom template tag is the way.
在任何适当的应用程序中,创建一个文件 templatetags/random_numbers.py
(如果没有其他自定义模板标签,则创建一个空的 templatetags/__ init __.py
),其中包含以下内容:
In any appropriate application, create a file templatetags/random_numbers.py
(and an empty templatetags/__init__.py
if you don't have any other custom template tags) with the following contents:
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)
然后,在模板中像这样使用它:
Then, in your template use it like this:
{% 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/
More documentation on custom tags: https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/
这篇关于如何在Django模板python中生成随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!