Python

Addition of two numbers in django python

Addition of two numbers in django python, someone asked me to explain?

In this tutorial I will show you how to add two numbers in django framework python program.

urls.py:

Defame the URL pattern to map the view.

from django.urls import path
from . import views

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

views.py:

In django view render the template and handle the form submission. 

def addition(request):
     
     if request.method == 'POST':
         try:
             num1 = request.POST.get('num1')
             num2 = request.POST.get('num2')
             result = eval(num1) + eval(num2)
             context ={'result' : result}
             return render(request,"app/addition.html", context)
         except Exception as e:
             print(f"Error: {e}")
     return render(request,"app/addition.html")

addition.html:

Create a simple HTML form with two input text boxes and submit button field. On form submission you can handle the addition operation and return the result.

<div class="container" style="margin-top:100px;">
    <div class="row">
      <div class="col-12">
        <h2> Addition </h2>

        <form action="{% url 'addition' %}" method="post">
            {% csrf_token %}
            <label for="num1">Number 1: </label>
            <input type="text" name="num1" class="form-control">
            <label for="num2">Number 2: </label>
            <input type="text" name="num2" class="form-control"> <br>
        <button type="submit"> Add </button> <br>
        <p> The result is : {{ result }} </p>
        </form>
       
      </div>
    </div>
  </div>

RESULT:

Addition django

VIDEO GUIDE:

Post your comments / questions