Skip to content
Advertisement

Django Error – unsupported operand type(s) for -: ‘str’ and ‘int’

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:

from django.shortcuts import render
from django.http import HttpRequest

def index(request):
    nor = request.GET.get('nor')
    mc = request.GET.get('mc')
    repaired = request.GET.get('repaired')
    if isinstance(nor, int):
        if repaired == 'yes':
            if mc == 'yes':
                summary = nor*20000+30000
            else:
                summary = nor*20000
        else:
            if mc == 'yes':
                summary = nor*20000-20000
            else:
                summary = nor*20000-50000
    else:
        summary = 'Try again'
    return render(request, 'index.html', {'summary':summary})

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.

def index(request):
    nor = request.GET.get('nor')
    mc = request.GET.get('mc')
    if nor:   # check if parameter exist.
        nor = int(nor) 
    repaired = request.GET.get('repaired')
    if isinstance(nor, int):
        if repaired == 'yes':
            if mc == 'yes':
                summary = nor*20000+30000
            else:
                summary = nor*20000
        else:
            if mc == 'yes':
                summary = nor*20000-20000
            else:
                summary = nor*20000-50000
    else:
        summary = 'Try again'
    return render(request, 'index.html', {'summary':summary})

You can try-catch block around your type conversion to handle other exceptions.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement