0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.