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:
VIDEO GUIDE:
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- The request was aborted: Could not create SSL/TLS secure channel -Error in Asp.net
Related Article