Django文件下载?

2024-09-29 23:15:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个视图“ans_page”和“downloads”,其中“ans_page”生成一个文件(库.csv)在“output”目录中,进一步“ans_page”呈现一个名为答案.html“它显示了一个包含数据的表和一个按钮,可以从名为FragBuild的应用程序的一部分”output“目录中下载文件,按钮提供了一个与“下载”视图URL相关联的超链接,我的期望是,如果有人点击下载按钮,它应该开始下载,但它显示一个错误,而不是如下所示:

视图

def Downloads(request):

    file_path = os.path.join(os.path.split(os.path.abspath(__file__))[0],'output','library.csv')
    file_wrapper = FileWrapper(file(file_path,'rb'))
    file_mimetype = mimetypes.guess_type(file_path)
    response = HttpResponse(file_wrapper, content_type=file_mimetype )
    response['X-Sendfile'] = file_path
    response['Content-Length'] = os.stat(file_path).st_size
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str('library.csv') 

网址如下:

^{pr2}$

启动下载的html按钮如下:

<div class="">
     <button class="btn btn-primary" style="width:40; margin-bottom: 30px; margin-left: 300px "><a href="{% url 'Downloads' %}"> Download Peptide as CSV file  </a> </button>
</div>

但当我点击一个按钮开始下载时,它显示了一个错误:

ValueError at /ans_page/Downloads The view FragBuild.views.Downloads didn't return an HttpResponse object. It returned None instead.

我怎样才能解决这个问题我一直在努力。在


Tags: 文件csvpath目录视图outputosresponse

热门问题