2017-07-27 120 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) 
相关问题