I have a Django code that must do some math, but I continuously get the following error:
unsupported operand type(s) for -: ‘str’ and ‘int’
Here is the code:
JavaScript
x
22
22
1
from django.shortcuts import render
2
from django.http import HttpRequest
3
4
def index(request):
5
nor = request.GET.get('nor')
6
mc = request.GET.get('mc')
7
repaired = request.GET.get('repaired')
8
if isinstance(nor, int):
9
if repaired == 'yes':
10
if mc == 'yes':
11
summary = nor*20000+30000
12
else:
13
summary = nor*20000
14
else:
15
if mc == 'yes':
16
summary = nor*20000-20000
17
else:
18
summary = nor*20000-50000
19
else:
20
summary = 'Try again'
21
return render(request, 'index.html', {'summary':summary})
22
Here is also the URL where I want to get “nor” from:
http://localhost:8000/mechanical/?nor=4&mc=yes&repaired=no&submit=Submit
Advertisement
Answer
Query string params are always string, you need to convert them to desired type. Here you need to convert string to int.
JavaScript
1
21
21
1
def index(request):
2
nor = request.GET.get('nor')
3
mc = request.GET.get('mc')
4
if nor: # check if parameter exist.
5
nor = int(nor)
6
repaired = request.GET.get('repaired')
7
if isinstance(nor, int):
8
if repaired == 'yes':
9
if mc == 'yes':
10
summary = nor*20000+30000
11
else:
12
summary = nor*20000
13
else:
14
if mc == 'yes':
15
summary = nor*20000-20000
16
else:
17
summary = nor*20000-50000
18
else:
19
summary = 'Try again'
20
return render(request, 'index.html', {'summary':summary})
21
You can try-catch block around your type conversion to handle other exceptions.