C0deSlayer
C0deSlayer

Reputation: 45

Python list: list index out of range

I am not so much familiar with python and got this code from a friend of mine and need some community help here to solve this issue.I'm getting "list index out of range" error from the following line.

days = list(zip(Leave_type.objects.filter(type=leavetype).values_list('max_days', flat=True))[0])

Note: I have already execute migrations and setup my database already.

def timeoffapply(request):

if not request.session.get('id', None):
    return render(request, 'login.html')
else:
    stdate = request.POST['startDate']
    enddate = request.POST['endDate']
    leavetype = request.POST['leaveType']
    days = list(zip(Leave_type.objects.filter(type=leavetype).values_list('max_days', flat=True))[0])
    d1 = datetime.strptime(stdate, "%Y-%m-%d")
    d2 = datetime.strptime(enddate, "%Y-%m-%d")
    d3 = abs((d2 - d1).days)+1
    empid = (request.session['id'])[0]
    countdays = Leave.objects.filter(Emp_id = empid,type=leavetype).aggregate(Sum('days'))
    if countdays['days__sum'] == None:
        finaday = (days[0] - 0)
    else:
        finaday=(days[0] - countdays['days__sum'])
    if enddate>=stdate:
        if finaday >= d3:
            getleaveid = list(zip(Leave_type.objects.filter(type=leavetype).values_list('id', flat=True))[0])
            split_lt_id = ("".join(str(e) for e in getleaveid))
            empid = (request.session['id'])[0]
            get_emp_name = list(zip(Employee.objects.filter(id=empid).values_list('name', flat=True))[0])
            get_emp_name = ("".join(str(e) for e in get_emp_name))
            empid = (request.session['id'])[0]
            leave_id = Leave.objects.all().count()
            test = Leave(id=(leave_id + 1), name=get_emp_name, type=leavetype, start_date=stdate, end_date=enddate,
                         days=d3,
                         status="pending")

            test.Emp_id_id = empid
            test.leave_type_id_id = split_lt_id
            test.save()
            return HttpResponseRedirect('/')
        else:
            qs = Leave.objects.all().filter(Emp_id=(request.session['id'])[0])
            context = {
                "qs": qs,
                "error": "true",
                "msg": "You are allowed to have holidays for " + str(finaday) + " days in " +str(leavetype)
            }
            return render(request, 'timeoff.html', context)

Upvotes: 1

Views: 309

Answers (2)

r_zelazny
r_zelazny

Reputation: 557

The problem is simply that the queryset returned from the Leave_type model is empty; therefore you cannot access it.

Upvotes: 1

Ritesh Agrawal
Ritesh Agrawal

Reputation: 821

There can be a case that list returned from Leave_type.objects.filter(type=leavetype).values_list('max_days', flat=True) is empty and you are accessing first element in the empty list using [0]. So causing list index out of range error.

Upvotes: 3

Related Questions