简体   繁体   中英

Python script to django html output

I want to put python script output to HTML using Django with a button. 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:

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:

<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).

# 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). 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.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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