TheLifeOfSteve TheLifeOfSteve - 6 months ago 12
Ajax Question

Getting a ValueError: invalid literal for int() with base 10: '' error and don't know why

I know this has been asked before, but for my circumstance, I can't seem to figure out why this is being thrown

When I try to run my calculations, I am given this error from my console:

ValueError: invalid literal for int() with base 10: ''


and it is saying its coming from

File "/var/sites/live_mbpathways/moneybroker/apps/investments/ajax.py", line 30, in calc_cdic
investments = Investment.objects.all().filter(plan = plan, financial_institution=fiid, maturity_date__gte = now).order_by('maturity_date').exclude(id=investment_id)


Does anyone know why this could be happening?

Here is my ajax.py where that code is located:

@login_required
@moneybroker_auth
@csrf_exempt
def calc_cdic(request, plan, investment_id=None, *args, **kwargs):
from investments.models import Investment
from financial_institutions.models import FinancialInstitution
from profiles.models import Profile
from plans.models import Plan
from datetime import datetime
now = datetime.now()
json = {}
data = request.POST

if request.is_ajax():
total = 0
fiid = data.get('financial_institution')
amt = data.get('amount') or 0
pay_amt = data.get('pay_amount') or 0
mat_amt = data.get('maturity_amount') or 0
investments = Investment.objects.all().filter(plan = plan, financial_institution=fiid, maturity_date__gte = now).order_by('maturity_date').exclude(id=investment_id)
for i in investments:
total += i.maturity_amount
print total
json['total'] = float(str(total))
json['amt'] = float(str(amt))
json['pay_amt'] = float(str(pay_amt))
json['mat_amount'] = float(str(mat_amt))
json['fiid'] = fiid
print json

return HttpResponse(simplejson.dumps(json), mimetype='application/json')

Answer

The int() function is throwing an exception because you are trying to convert something that is not a number.

I suggest that you might consider using debugging print statements to find out what plan's and fiid's are initally and how they change.

Another thing you can do is wrap the call to int() using try/catch

val='a'
try:
    int_val = int(val)
except ValueError:
    print("Failure w/ value " + val)