[Fixed]-Simple Calculator using HTML forms in python django

1👍

is your view getting called or you’re not able to get any result.

One thing even if view gets control, is sure that your code will break when sym is =
because it will be handled in the first if and it doesn’t handle =

If your form isn’t submitted, i think you need to handle it through Javascript and AJAX.

0👍

In my view.py file i had written the operations such as add,sub,mul in the end. So, i just put them at the top of the file below import. It worked.

Views.py file:

from django.shorcuts import render

def add(a,b):
 return a+b

def mul(a,b):
 return a*b

def sub(a,b):
 return a-b

def operation(request):
  if 'sym' in request.GET:
        if request.GET['sym'] == 'add':
            first=request.GET['result']
            opsign='\+'
            return render(request,'calculator.html',{'result':first,'prev_val':first,'curr_val':second,'opsign':opsign}) 
  elif request.GET['sym'] == '=':
        if 'prev_val' in request.GET and request.GET['prev_val']:
            first=request.GET['prev_val']
        if 'result' in request.GET and request.GET['result']:
            second=request.GET['result']    
        try:
            result=add(10,20)
        except ValueError:
            err="Error: Incorrect Number"
        except ZeroDivisionError:
            err="Error: Division by zero"
        return render(request,'calculator.html',{'result':result,'error':err}) 
    else:
        return render(request,'calculator.html',{'error':'No Operation selected'}) 

Leave a comment