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

Download file from Django Project root using a button

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

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

当用户:

  1. 在框中写一个 subreddit 名称
  2. 按下按钮'Get Data'

发生了什么:

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

现在的问题是: 我想要带 'Export to 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 2

Link 3

Link 4

您必须先创建 response object 才能将 headers 分配给它。

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