def list(request):
    # Handle file upload
    #Document.objects.all().delete()
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            #newdoc = Document(docfile = request.FILES['docfile'])
            #newdoc.save()
            #Root Image File
            newdoc = BasicImage(docfile = request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            #return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
            imagenm = newdoc.docfile.url
            #[nameList,django_file,returnstr] = classification(imagenm)
            [nameListList,djangoFileList,returnStrList] = classification(imagenm)
            
            #for each detection result, save them in the database
            print '-----------------------------'
            print len(nameListList)
            print '-----------------------------'
            
            for i in range(0,len(nameListList)):
                nameList = nameListList[i]
                returnstr = returnStrList[i]
                django_file = djangoFileList[i]
                
                subImage = Document(basefile=newdoc)
                
    
                #results = Result.objects.all()
                subImage.catagory = returnstr
                subImage.imgfile = django_file
                subImage.top1 = subImage.catagory+'processed/'+nameList[0]
                subImage.top2 = subImage.catagory+'processed/'+nameList[1]
                subImage.top3 = subImage.catagory+'processed/'+nameList[2]
                
                #look up the database to fetch name and url of these three top bags
                [subImage.top1_url,subImage.top1_name] = fetchDatafromSQL(1,subImage)
                [subImage.top2_url,subImage.top2_name] = fetchDatafromSQL(2,subImage)
                [subImage.top3_url,subImage.top3_name] = fetchDatafromSQL(3,subImage)
                
                subImage.save()
                
            my_images = Document.objects.filter(basefile_id=newdoc.id)
            return render(request, 'myapp/index.html', {'newdoc':newdoc,'my_images':my_images})
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )