得到一个 ValueError: invalid literal for int() with base 10: '' 错误,不知道为什么

The*_*eve 3 python django ajax django-views

我知道以前有人问过这个问题,但就我的情况而言,我似乎无法弄清楚为什么会抛出这个问题

当我尝试运行我的计算时,我的控制台给出了这个错误:

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

它说它来自

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)
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么会发生这种情况?

这是我的 ajax.py 代码所在的位置:

@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')
Run Code Online (Sandbox Code Playgroud)

oct*_*bus 5

int() 函数抛出异常,因为您正在尝试转换不是数字的内容。

我建议您可以考虑使用调试打印语句来找出最初的计划和 fiid 以及它们如何更改。

您可以做的另一件事是使用 try/catch 包装对 int() 的调用

val='a'
try:
    int_val = int(val)
except ValueError:
    print("Failure w/ value " + val)
Run Code Online (Sandbox Code Playgroud)