简体   繁体   English

Python脚本到django html输出

[英]Python script to django html output

I want to put python script output to HTML using Django with a button.我想使用带有按钮的 Django 将 python 脚本输出放到 HTML 中。 When the user clicks the button again and it changes the random number again.当用户再次单击该按钮并再次更改随机数时。

import random
num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
print(random.choice(num))

In your views.py file inside your app (all inside your Django project)... From the function that will display this random number, put:在您的应用程序中的views.py文件中(全部在您的 Django 项目中)...从将显示此随机数的函数中,输入:

from random import choice
def <function_you_are_using> (request):   
     nums = [1,2,3,4,5]
     context = {"number": choice(nums)}
     return render(request, '<function_you_are_using>', context)

Then, in your HTML, put:然后,在您的 HTML 中,输入:

<h1>{{ number }}</h1>

That should display the random-choice number.那应该显示随机选择数。 Hope it helps.希望能帮助到你。

You could render this out in a template.您可以在模板中呈现它。 This would take the function you have above and place it into a function based view.这将采用您上面的函数并将其放入基于函数的视图中。 the function will take your list of numbers and assign the random number to the variable random_number, which is then passed in as context (on the return line).该函数将获取您的数字列表并将随机数分配给变量 random_number,然后将其作为上下文传入(在返回行上)。

# views.py
def random_num(request):
    num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
    random_number = random.choice(num)
    return render(request, 'random-number.html', {'random_number': random_number})

To pass this into the HTML template (see HTML below).将此传递到 HTML 模板(请参阅下面的 HTML)。 This is taking the 'random_number' variable that you assigned in your view and rendering it in place of {{ random_number }} when the page loads.这是采用您在视图中分配的 'random_number' 变量,并在页面加载时将其呈现在 {{ random_number }} 的位置。

<!-- random-number.html -->
<html>
    <h1>Random Number: {{ random_number }}</h1>

    <form action="{% url 'random-number' %}">
        <input type="submit" value="Get New Number"/>
    </form>
</html>

Sort of a lazy workaround since the "button" is just refreshing the page to call the function again and generate a new random number.有点懒惰的解决方法,因为“按钮”只是刷新页面以再次调用该函数并生成一个新的随机数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM