Run a Python Function by Clicking an HTML Button in Django

One of the most common tasks I encounter while working with Django is triggering backend Python logic through frontend actions. If you’re building web applications, you’ll often want to run a Python function when a user clicks a button on your webpage.

In Django, this might seem tricky at first, especially if you’re new to web development. But it’s easy once you understand how Django handles HTTP requests and how to connect frontend buttons to backend views.

In this tutorial, I’ll walk you through how to run a Python function by clicking an HTML button in Django. I’ll cover multiple methods, including the classic form submission and AJAX calls, so you can choose the one that fits your project best.

Understand the Basics: How Django Handles Button Clicks

When you click a button on a webpage, it usually triggers an HTTP request to the server. Django listens for these requests and routes them to the appropriate view functions, where your Python code runs.

There are two common ways to trigger a Python function from a button click:

  1. Form submission: The button is inside a form, and clicking it submits the form to a Django view.
  2. AJAX call: The button triggers a JavaScript function that sends an asynchronous request to the server without reloading the page.

Let’s explore both methods with full examples.

Check out Python Django: Get Admin Password

Method 1: Run a Python Function Using a Form Submit Button

This is the most straightforward method. You place a button inside a form, and when the user clicks it, the form submits data to a Django view that runs your Python function.

Step 1: Create a Django Project and App

If you haven’t already, start a new Django project and app:

django-admin startproject myproject
cd myproject
python manage.py startapp myapp

Add myapp to your INSTALLED_APPS in settings.py.

Step 2: Define the View Function

In myapp/views.py, define a view that runs your Python function when the form is submitted.

from django.shortcuts import render
from django.http import HttpResponse

def multiply_numbers(request):
    result = None
    if request.method == 'POST':
        # Example: Multiply two numbers
        num1 = int(request.POST.get('num1', 0))
        num2 = int(request.POST.get('num2', 0))
        result = num1 * num2
    return render(request, 'myapp/multiply.html', {'result': result})

Here, I created a simple multiply function that takes two numbers from the form and returns their product.

Read: Upload Image File in Django

Step 3: Create the HTML Template

Create a template file at myapp/templates/myapp/multiply.html:

<!DOCTYPE html>
<html>
<head>
    <title>Multiply Two Numbers</title>
</head>
<body>
    <h2>Multiply Two Numbers</h2>
    <form method="post">
        {% csrf_token %}
        <input type="number" name="num1" placeholder="Enter first number" required>
        <input type="number" name="num2" placeholder="Enter second number" required>
        <button type="submit">Multiply</button>
    </form>

    {% if result is not None %}
        <h3>Result: {{ result }}</h3>
    {% endif %}
</body>
</html>

This form collects two numbers and submits them to the same view.

Step 4: Configure URL Patterns

In myapp/urls.py, add the URL for this view:

from django.urls import path
from . import views

urlpatterns = [
    path('multiply/', views.multiply_numbers, name='multiply_numbers'),
]

Include myapp.urls in the main myproject/urls.py:

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

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

Step 5: Run the Server and Test

Start the Django server:

python manage.py runserver

Visit http://127.0.0.1:8000/multiply/ in your browser. Enter two numbers and click the Multiply button. You will see the result displayed on the page.

You can see the output in the screenshot below.

django button

Check out Django vs ReactJS

Method 2: Run a Python Function Using AJAX and an HTML Button

Sometimes, you want to run a Python function without refreshing the page. This is where AJAX comes in handy.

Step 1: Define the AJAX View

In myapp/views.py, add a view that processes AJAX requests:

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt  # For simplicity; better to use CSRF tokens in production
def ajax_multiply(request):
    if request.method == 'POST':
        num1 = int(request.POST.get('num1', 0))
        num2 = int(request.POST.get('num2', 0))
        result = num1 * num2
        return JsonResponse({'result': result})
    return JsonResponse({'error': 'Invalid request'}, status=400)

Step 2: Create the AJAX HTML Template

Create myapp/templates/myapp/ajax_multiply.html:

<!DOCTYPE html>
<html>
<head>
    <title>AJAX Multiply</title>
    <script>
        function multiplyNumbers() {
            const num1 = document.getElementById('num1').value;
            const num2 = document.getElementById('num2').value;

            fetch('/ajax-multiply/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRFToken': getCookie('csrftoken')  // CSRF token for security
                },
                body: `num1=${num1}&num2=${num2}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.result !== undefined) {
                    document.getElementById('result').innerText = 'Result: ' + data.result;
                } else {
                    document.getElementById('result').innerText = 'Error occurred';
                }
            });
        }

        // Helper function to get CSRF token from cookies
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    </script>
</head>
<body>
    <h2>Multiply Two Numbers Using AJAX</h2>
    <input type="number" id="num1" placeholder="Enter first number" required>
    <input type="number" id="num2" placeholder="Enter second number" required>
    <button onclick="multiplyNumbers()">Multiply</button>

    <h3 id="result"></h3>
</body>
</html>

Step 3: Add URL Patterns for AJAX

In myapp/urls.py add:

urlpatterns = [
    path('multiply/', views.multiply_numbers, name='multiply_numbers'),
    path('ajax-multiply/', views.ajax_multiply, name='ajax_multiply'),
]

Step 4: Test the AJAX Button

Run your server and visit http://127.0.0.1:8000/ajax-multiply/. Enter numbers and click the Multiply button. The result will appear instantly without a page reload.

You can see the output in the screenshot below.

django button onclick go to url

Read Change Django Version in Python

Tips from My Experience

  • For simple tasks, form submission is quick and easy.
  • Use AJAX when you want a smoother user experience without page reloads.
  • Always handle CSRF protection properly in production (the example uses @csrf_exempt for simplicity).
  • Make sure your URLs and views are well organized to keep your project maintainable.
  • You can extend these examples to run any Python logic triggered by button clicks.

Running Python functions from HTML buttons in Django is a fundamental skill for creating interactive web apps. Whether you prefer traditional form submissions or modern AJAX calls, Django’s flexibility makes it easy to connect frontend actions with backend logic.

If you want to dive deeper, consider exploring the Django REST framework for building APIs that your frontend can interact with asynchronously.

I hope this tutorial makes it easier for you to implement button-triggered Python functions in your Django projects.

Other Python Django tutorials you may find useful:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.