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

2024-05-05

So, this is the webpage I'm creating atm with Django 1.8: enter image description here

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

当用户:

  1. 在框中写下 Reddit 子版块名称
  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')
]

This is the error I'm getting when clicking the button: enter image description here

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

预先感谢您的帮助/指导

方便的链接:

Link 1 https://stackoverflow.com/questions/41711536/exporting-django-objects-model-in-csv

Link 2 https://stackoverflow.com/questions/20040965/how-to-export-data-in-python-with-excel-format

Link 3 https://stackoverflow.com/questions/37012924/python-object-does-not-support-item-assignment

Link 4 https://stackoverflow.com/questions/8542343/object-does-not-support-item-assignment-error


您必须首先创建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 https://stackoverflow.com/questions/36392510/django-download-a-file

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用按钮从 Django 项目根下载文件 的相关文章

随机推荐