【问题标题】:Download file from Django Project root using a button使用按钮从 Django 项目根目录下载文件
【发布时间】:2017-07-29 00:51:31
【问题描述】:

所以,这是我用 Django 1.8 创建的网页:

希望用户能够将数据导出为 .csv。

当用户:

  1. 在框中写一个 subreddit 名称
  2. 按下“获取数据”按钮

会发生什么:

  1. 它创建了一个 test.csv(保存在项目的根目录中)
  2. 使用 Praw 检索数据
  3. 数据被插入到 .csv 文件中
  4. 数据呈现给用户查看

现在的问题是: 我想要“导出到 Excel”按钮,从 Django 项目的根目录下载生成的文件。

这是给按钮的:

 <form class="export_excel" id="login_form" action="/app/export">
    {% csrf_token %}
    <button class="btn btn-lg btn-primary btn-block" value="Export to Excel" type="submit">Export To Excel</button>
 </form> 

这是app/views.py:

def export(request):

    filename = "test.csv" # this is the file people must download

    response['Content-Disposition'] = 'attachment; filename=' + filename
    response['Content-Type'] = 'application/vnd.ms-excel; charset=utf-16'
    return response

这是app/urls.py:

# app/urls.py
from django.conf.urls import url
from . import views

# Create your urls here.
urlpatterns = [
(...)
  url(r'^export/$', views.export, name='export')
]

这是我在单击按钮时遇到的错误:

问题是:如何让用户使用按钮导出文件?我做错了什么?

提前感谢您的帮助/指导

方便的链接:

Link 1

Link 2

Link 3

Link 4

【问题讨论】:

  • 我不知道reddit的东西,但是这种方法看起来非常复杂,你为什么要保存生成的文件?看过像stackoverflow.com/questions/5146539/… 这样的例子,是创建 .csv 并直接发送给用户(或者甚至流式传输更大的文件)?
  • 这是我能想到的唯一解决方案。不,谢谢分享。我现在要去看看@andipla

标签: python django excel csv reddit


【解决方案1】:

您必须首先创建response 对象才能为其分配标头。

def export(request):
    filename = "test.csv" # this is the file people must download
    with open(filename, 'rb') as f:
        response = HttpResponse(f.read(), content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=' + filename
        response['Content-Type'] = 'application/vnd.ms-excel; charset=utf-16'
        return response

取自here

【讨论】:

  • 很好,正在下载。尽管如此,这是下载此按钮所在页面的代码,没有包含数据的区域。我只是想要数据部分,这就是为什么提到要获取已经在服务器中的文件
  • 谢谢,这很好用。只需对response = HttpResponse(f.read(), content_type='application/vnd.ms-excel') 进行一点编辑,您就有一个额外的“h”
猜你喜欢
  • 1970-01-01
  • 2018-10-12
  • 1970-01-01
  • 2019-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多