使用button从Django Project root下载文件
所以,这是我用Django 1.8创buildatm的网页:
希望用户能够以.csv格式导出数据。
当用户:
- 在箱子里写一个subreddit的名字
- 按下“获取数据”button
怎么了:
- 它创build了一个test.csv(保存在项目的根目录)
- 数据是使用Praw检索的
- 数据被插入.csv
- 数据呈现给用户看
现在的问题是:我想要button“导出到Excel”,从Django项目的根下载生成的文件。
这是button:
<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') ]
这是我点击button时得到的错误:
问题是:如何让用户使用button导出文件? 我究竟做错了什么?
预先感谢您的帮助/指导
方便的链接:
链接1
链接2
链接3
链接4
您必须先创buildresponse
对象才能为其分配标题。
def export(request): filename = "test.csv" # this is the file people must download with open(filename, 'rb') as f: response = HttpResponse(fh.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
从这里采取