Home > Software design >  A Simple Calculator using Django
A Simple Calculator using Django

Time:10-08

I want to create a website where the user is asked to type a given number to get the square number and the square root.

This is from index.html:

  <div class="d-flex typeW">

    <form action="add">
    Enter a number : <input type="text" name="num1">

    <input type="submit">
  </form>
  </div>

This is from the result page (where you can see the result):

<div class="d-flex title2">

    <h2>

    {% block content %}



      {{result}}

    {% endblock %}
    <br><br>

This is from view:

def add(request):
num1 = int(request.GET["num1"])
return render(request, 'result.html' , {result2: num1 * num1})

Now I want to take the square root of that number but I'm not sure how.

How do I take one input and then do two calculations by using two functions?

help much appreciated

CodePudding user response:

Simply do two calculations in your view and return both results within the context. You can then access all values in the context and render them in the template.

import math

def add(request):

    # Get the user input
    num1 = int(request.GET["num1"])

    # Calculate square
    num1_square = num1 ** 2

    # Calculate root 
    num1_root = math.sqrt(num1)

    # return context
    context = {
        'square': num1_square,
        'root': num1_root
    }

    return render(request, 'result.html' , context)
# template

<div class="d-flex title2">

    <h2>

    {% block content %}

      {{ square }}

      {{ root }}

    {% endblock %}
    <br><br>
  • Related