Run Python function by clicking on HTML Button in Django

In this Python Django tutorial, I will explain how to run python function by clicking on HTML button in Django.

While working on a Django project, I need an HTML button for calling the python function. So, I have done the research and finally create an HTML button that prints table multiplication on click.

So, here we will see:

  • How to set up project in Django
  • How to create HTML button to execute python function in Django
  • Run Python function by clicking on HTML Button in Django to get multiplication table
  • How to use for loop in Django template tag
  • How to use range function in Django
  • Create Django Form using FormClass

At the end of this article, you can download the code for executing the python script with the click of an HTML button.

This is what we will build here.

execute python multiplication table function in django
Run Python function by clicking on HTML Button in Django to get multiplication table

Run Python function by clicking on HTML Button in Django

Now, let us see, step by step how to run the Python function on button click and display table multiplication in Django.

Set up Django Project

Firstly, we need to establish a project in Django using the below-given command. Here HTMLButtonProject is the name of the project.

django-admin startproject HTMLButtonProject

Within the Django project, create a Django app named MyApp using the command as follows.

python manage.py startapp MyApp
html button to run python function in django
Set Up Django Project

Open the settings.py file located in the project directory, and add MyApp to the INSTALLED_APP list.

how to run python function by clicking on HTML button
Install MyApp

A request in Django first comes to urls.py located inside the project directory and then goes to the matching URLs in urls.py inside the app directory. Add the below code in it.

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('MyApp.urls')),
]

Also, check: Difference between app and project in Django

READ:  Scipy Signal - Helpful Tutorial

Create Django Form

Create the Django form that the MyApp application will use to take input a number from the user. Add the following code to the forms.py file we created inside the app directory.

from django import forms

class TableForm(forms.Form):
    num = forms.IntegerField(label='Please Enter Number:')

Here, we create a form using forms.Form class named TableForm. And it has num as Django IntegerField. Additionally, we change its label by passing the label keyword.

Run Python function by clicking on HTML Button in Django to get multiplication table

Create a subdirectory called Templates in the main project directory to store the HTML file of a Django application.

Open the settings.py file, and update the DIRS to refer to the Templates folder’s location.

execute python code by django html button
Set Templates Folder Location

To define the frontend for the table multiplication function on the HTML button click, create an HTML file named home.html inside the Templates folder. And add the below-given code.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Table Multiplication</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

</head>

<body>
    <div class="mt-md-5">
        <div class="pl-sm-5">
            <div class="pr-sm-5">
                <h3 align="center">Welcome to PythonGuides</h3>
                <br>
                <hr>
                <form method="POST">
                    {% csrf_token %}
                    <table>
                        {{ form.as_table }}
                    </table>
                    <button type="submit" class="btn btn-success">Print Table</button>
                </form>
                <br>
                <hr>
                <p>Number to print its multiplication table:{{Number}}</p>
                <br>
                <hr>
                {% for x in range %}
                {{ Number }} x {{x}} = {% widthratio Number 1 x %} <br>
                {% endfor %}
            </div>
        </div>
    </div>

    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js"
        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
        crossorigin="anonymous"></script>
</body>

</html>
  • First, load your CSS by adding the stylesheet’s link to your page’s header before any other stylesheets.
  • Then, to add bootstrap padding and spacing use the div class mt-md-5, div class pl-sm-5, and div class pr-sm-5 respectively.
  • To build the form that we use to input a number from the user, we use the form tag with the POST method. Then, use the csrf_token to protect the form from cyber attacks and form.as_table to render the form field in table format.
  • Add a submit button to print the table multiplication. And, use the p tag and print the multiplication table. And then, we will use the for loop to get one value at a time from the sequence.
  • Then, we use this single value to get the table multiplication of the input number. To get the table multiplication, we are using a widthratio filter, and in the filter, (Number 1 x) simply means (Number * x).
  • Additionally, we use the h3, br, and hr tags to add a heading, break the line, and horizontal line respectively.
READ:  Upload a File in Python Tkinter

Read: Python Django form validation

Define View

To define the main logic, open the views.py file and add the code given below.

from django.shortcuts import render
from .forms import TableForm

# Create your views here.

def html_button(request):
    if request.method == "POST":  
        form = TableForm(request.POST)  
        if form.is_valid():  
            num = form.cleaned_data['num']
            return render(request, 'home.html', {'Number':num, 'range': range(1,11)})
    else:  
        form = TableForm()  
    return render(request,'home.html',{'form':form})
  • First, import the TableForm from the forms.py and create a view named html_button.
  • Then call the if statement and check whether the request method is POST.
    • If yes, we pass TableForm(request.POST) that binds the data to the form class, so we can do validation.
    • Now, call the is_valid method to validate the input entered by the user, and if validation success call the form cleaned_data[‘form field’] to validate the data.
    • Return home.html with num and range() function to get a list of numbers from 1 to 10 by passing to the render function.
  • If the request method is GET, the user is presented with a blank input field to enter the number using the render() function.

Now, we must map the view with the URL in order to call it, thus we must create a file called urls.py in the app directory. Include the code below in it.

from django.urls import path
from . import views

urlpatterns = [
path('', views.html_button, name='htmlbutton'),
]

Read: Python Django app upload files

Execute Django Application

To launch a development server type the below-given command in the terminal and run the server.

python manage.py runserver

It successfully opens the web page used to do table multiplication which looks like this.

Run Python function by clicking on HTML Button in Django
Run Python Function on HTML Button Click

Now, fill out the number whose table you want to print and click on the Print Table button.

create html button to execute python function in django
Table Multiplication Web Page

For example, here I enter the number 7 and it will print the table of 7 on clicking on the Print Table button.

using django create html button to execute python function
HTML Button Click Python

This is how we run the Python function by clicking on HTML Button using Django.

READ:  Python Django get enum choices

Download the complete code to Run Python function by clicking on HTML Button in Django

Here is the code:

Conclusion

With this, we have successfully created a Python function that will execute on an HTML button click. We have also learned to create a form using the Form Class that will take input from the user in the integer field.

Additionally, we have also covered the following topic

  • How to set up project in Django
  • How to create HTML button to execute python function in Django
  • Run Python function by clicking on HTML Button in Django to get multiplication table
  • How to use for loop in Django template tag
  • How to use range function in Django
  • Create Django Form using FormClass

Also, check the following tutorials on Python Django