2017-07-21 74 views
1

我有一個顯示Trainer名稱,位置等的索引視圖,以及一個下載他們的配置文件的按鈕(已經以數據庫的形式作爲pdf)。我根據一些參數搜索和過濾這些。現在我想能夠選擇其中的一些並下載選定的Trainer配置文件。我剛接觸Django並且無法弄清楚如何做到這一點。這是我的代碼。它說, 'FieldFile對象是不可調用的' views.py 高清下載(請求): 進口壓縮文件 進口OSDjango:壓縮選定的對象的pdf

file = zipfile.ZipFile("C:\\Downloads\\test.zip", "w") 

filelist = [] 
filelist+= 'Trainer.checkboxoption' in request.REQUEST 
for i in filelist: 
    file.write(i) 

file.close() 
return render(request,'trainer/index.html') 

的index.html

<form action="download/" method="post"> 
      <div class="caption"> 
       <div > 
        <table style="width:100%" class="table"> 
         <tr> 
          <th>#</th> 
          <th>Name</th> 
          <th>Technology</th> 
          <th>Location</th> 
          <th> View</th> 
          <th>Download</th> 
          <th>Delete</th> 
         </tr> 
         {% for trainer in all_trainers %} 
         <tr> 
          <td><input type="checkbox" id="trainer{{ forloop.counter }}" name="trainer" value="{{ trainer.id }}"></td> 
           <td> <a href="/trainer/{{ trainer.id }}">{{ trainer.name }}</td> 
           <td>{{ trainer.technology }}</td></a> 
           <td>{{ trainer.location }}</td> 
           <!-- View Details --> 
           <td><a href="/trainer/{{ trainer.id }}" class="btn btn-primary btn-sm">View Details</a></td> 

           <td><a href="../media/{{ trainer.trainer_profile }}" class="btn">Download PDF</a></td> 

           <!-- Delete Album --> 
           <td><form action="trainer/{{trainer.id }}/delete/" method="post"> 
            {% csrf_token %} 
            <input type="hidden" name="trainer_id" value="{{ trainer.id }}" /> 
            <button type="submit" class="btn btn-default btn-sm"> 
             <span class="glyphicon glyphicon-trash"></span> 
            </button> 
           </form></td> 
          </tr> 
         {% endfor %} 
        </table> 
       </div> 
      </div> 
      <input type="submit" value="Download ZIP"> 
     </form> 
+0

它爲什麼需要在zip中? –

+0

這將是困難的下載他們每個人單獨..有超過1000個文件 –

+0

好吧,我誤解了。 –

回答

0

views.py:

def download(request): 
     import zipfile 
     filef = zipfile.ZipFile("test.zip", "w") 
     var = request.POST.getlist('checks') 
     pdfprofile = [] 
     for i in var: 
      trainer= Trainer.objects.get(pk=i) 
      pdfprofile.append(trainer.trainer_profile) 

     for i in pdfprofile: 
      filef.write("D:\\Django\\myproduct\\media\\"+str(i)) 
     filef.close() 

     response = HttpResponse(open("test.zip", "rb").read(), content_type='application/zip') 
     response['Content-Disposition'] = 'attachment; filename=test.zip' 
     return response