使用按钮从 Django 项目根下载文件

Tia*_*ica 1 python csv django excel reddit

所以,这是我用 Django 1.8 创建 atm 的网页: 在此处输入图片说明

希望用户能够将数据导出为 .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> 
Run Code Online (Sandbox Code Playgroud)

这是在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
Run Code Online (Sandbox Code Playgroud)

这是在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')
]
Run Code Online (Sandbox Code Playgroud)

这是我单击按钮时遇到的错误: 在此处输入图片说明

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

预先感谢您的帮助/指导

方便的链接:

链接 1

链接 2

链接 3

链接 4

nik*_*k_m 5

您必须首先创建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
Run Code Online (Sandbox Code Playgroud)

取自这里

  • 谢谢,这很好用。只需对 `response = HttpResponse(f.read(), content_type='application/vnd.ms-excel')` 做一点编辑,你就有了一个额外的 'h' (2认同)