2017-07-27 35 views
1

我開發了一個數據科學web應用程序,可以生成各種統計分析相關的圖表。統計函數從Django應用程序執行,名爲「ProtocolApp」,其中我有一個目錄爲「Statistical_protocols」,而「Stat_Learning」項目爲基目錄。我的程序正在生成一些圖像文件和.csv輸出文件,其中包含項目「Stat_Learning」的基本目錄,「manage.py」存在的同一目錄「。如何在Django中爲下載鏈接添加一個目錄?

在模板中,我提供了所有文件的鏈接這樣的:

模板:

{% extends 'protocol/base.html' %} 

{% load static %} 


{% block content %} 

<style type="text/css"> 

    table { 

    margin-bottom: 20px; 

    border-collapse: collapse; 
    border-spacing: 0; 
    width: 30%; 
    border: 1px solid #ddd; 
    bgcolor: #00FF00; 
} 

th, td { 
    border: none; 
    text-align: left; 
    padding: 8px; 
} 

tr:nth-child(even){background-color: #f2f2f2} 

</style> 



<div style="overflow-x:auto;"> 
    <table align="center"> 
    <tr> 
     <th align="center">Result files</th> 
    </tr> 
    {% for a in names %} 
    <tr> 
    {% if a %} 
     <td><a href="/virtual_env_dir/Base_rectory_of_the_project/{{a}}"> {{a}} </a> <br></td> 
    {% endif %} 
    </tr> 
    {% endfor %} 
    </table> 
</div> 


{% endblock %} 

有沒有爲所有文件提供通過這個基本目錄下載鏈接的方法

或有添加另一個名爲「下載」等目錄中的任何方法然後媒體目錄。因爲我正在使用媒體目錄上傳協議的輸入文件。

感謝

回答

1

試試這個:

創建這樣一個觀點:

def send_file(request): 
    import os, tempfile, zipfile, mimetypes 
    from django.core.servers.basehttp import FileWrapper 
    from django.conf import settings 
    filename  = settings.BASE_DIR + <file_name> 
    download_name ="example.csv" 
    wrapper  = FileWrapper(open(filename)) 
    content_type = mimetypes.guess_type(filename)[0] 
    response  = HttpResponse(wrapper,content_type=content_type) 
    response['Content-Length']  = os.path.getsize(filename)  
    response['Content-Disposition'] = "attachment; filename=%s"%download_name 
    return response 

創建一個網址,讓錨標記指向該網址。請記住將download屬性添加到您的定位標記

+0

你能解釋一點,這是怎麼回事這裏我很新,所以它很難對我來說,在我的情況 – jax

+0

這就是如何申請文件下載在適應這個代碼Django的。您可能需要閱讀https://docs.djangoproject.com/en/1.10/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment –

+0

但我沒有類似的文件到服務器,所以我可以定義不同的文件作爲內容類型。 – jax

0

我不確定這是否可以回答您的問題,但我工作的公司運行Django網站(1.10.5),我們傾向於使用上傳文件到媒體目錄django管理面板。管理面板還提供頁面編輯器,您可以在其中設置頁面的URL,然後放入到媒體文件的鏈接。 Django的定義的設置,使您可以通過任何根URL訪問媒體庫:

# URL that handles the media served from MEDIA_ROOT. Make sure to use a 
# trailing slash. 
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/" 
MEDIA_URL = "/media/" 

但是,如果你定義過程生成隨機命名的文件,您可以定義一個url的標準方式指向一些看法。視圖的僞代碼可能是這樣的:

def protocolView(request): 
    someListOfDirs = ... 
    context = { names: [] } 
    for directory in someListOfDirs: 
     for root, dirs, files in os.walk(directory): 
      for file in files: 
       if file is a generated file: 
        context["names"].append(file) 
    render(request, "template.html", context) 
相關問題