def get_loan_to_save(data, amount = None, lid = None):
    if not lid:
        l = Loan.objects.get(pk=data['loan.id'])
    else:
        l = Loan.objects.get(pk=lid)
    if not amount:
        amount = round(l.amount / l.instalments,2)
        if amount > l.remain:
            amount = l.remain 
        validate_amount(amount)

    if param_exist("id",data):
        p = Payment.objects.get(pk=data['id'])    
        prevAmount = p.amount
    else:
        p = Payment(loan=l)
        prevAmount = None
    
    if checkPayment(l,amount,prevAmount):
        if prevAmount:
            diff = float(prevAmount) - float(amount)
            l.remain = unicode(float(l.remain) + diff)
        else:
            l.remain = unicode(float(l.remain) - float(amount))

        p.amount=amount
        p.date=DateService.parseDate(data['date'])
    else:
        raise ValidationError(_('The entered amount is greater than the amount owed.'))
    return (l,p)
    if param_exist("id",req):
        p = Payment.objects.get(pk=req['id'])    
        prevAmount = p.amount
        
    else:
        p = Payment(loan=l)
        prevAmount = None
    
    if checkPayment(l,amount,prevAmount):
        if prevAmount:
            diff = float(prevAmount) - float(amount)
            l.remain = unicode(float(l.remain) + diff)
        else:
            l.remain = unicode(float(l.remain) - float(amount))

        p.amount=amount
        p.date=DateService.parseDate(req['date'])
        
        try:
            l.save()
        except _mysql_exceptions.Warning:
            pass        
        try:
            p.save()
        except _mysql_exceptions.Warning:
            pass        
        except Exception, e1:
            data = '{"success":false, "msg": "%s"}' % (e1.args)
    else:
        data = '{"success":false, "msg": "%s"}' % (_('The entered amount is greater than the amount owed.'))
    return data