2017-05-22 54 views
0

上傳文件夾中的csv文件,現在我想讓這些文件在python中傳遞一個列表來生成pdf。我如何在django中調用這個文件,或者有更好的方法來做到這一點?如何在django中上傳文件並傳遞給函數

這是我上傳的文件:

def subir_archivos(request): 
    if request.method == 'POST' and request.FILES['myfile']: 
      myfile = request.FILES['myfile'] 
      fs = FileSystemStorage() 
      filename = fs.save(myfile.name, myfile) 
      uploaded_file_url = fs.url(filename) 
      return render(request, 'subir_csv.html', { 
       'uploaded_file_url': uploaded_file_url 
      }) 
    return render(request, 'subir_csv.html') 

而且方法爲CSV傳遞給Python列表:

def csv_empresas(request): 
    lista = [] 

    with open('media/empresas.csv') as csvfile: 
     lector = csv.reader(csvfile, delimiter=',',quotechar='|') 
     for row in lector: 
      lista.append(row) 


    return render(request,'preparar_pdf.html',{"lista": lista}) 
+0

有啥問題,你面臨 – Exprator

+0

的問題是代碼:我需要從5個CSV文件進行PDF(傳遞Django的5名單函數視圖)和csv的名稱可以不同,所以我不知道如何將這5個列表傳遞給函數。 –

+0

有點難以解釋爲我的英語感到難過 –

回答

0

在上傳文件時,可以保存所有將文件上傳到媒體文件夾內的一個文件夾中

將上傳的文件保存在文件夾ca中的代碼大會另作upload_files

def subir_archivos(request): 
    if request.method == 'POST' and request.FILES['myfile']: 
     myfile = request.FILES['myfile'] 
     file_obj = myfile.read() 
     media_path = settings.MEDIA_ROOT 
     file_path= os.path.join(media_path, "upload_files") 
     if not os.path.isdir(file_path): 
      try: 
       os.makedir(file_path) 
      except OSError as e: 
       pass 
     file = os.path.join(file_path, myfile.name) 
     with open(file, 'wb') as f: 
      f.write(file_obj) 
     uploaded_file_url = os.path.join("/media", "upload_files", myfile.name) 
     return render(request, 'subir_csv.html', { 
       'uploaded_file_url': uploaded_file_url 
      }) 
    return render(request, 'subir_csv.html') 

,併爲獲得所有上傳的文件

import os 
def csv_empresas(request): 
    lista = [] 
    media_path = settings.MEDIA_ROOT 
    file_path= os.path.join(media_path, "upload_files") 
    files = os.listdir(file_path) 
    for file in files: 
     with open(file, 'rb') as csvfile: 
      lector = csv.reader(csvfile, delimiter=',',quotechar='|') 
      for row in lector: 
       lista.append(row) 
    return render(request,'preparar_pdf.html',{"lista": lista})