使用按钮从Django Project root下载文件 [英] Download file from Django Project root using a button

查看:346
本文介绍了使用按钮从Django Project root下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So, this is the webpage I'm creating atm with Django 1.8:

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

Want the user to be able to export the data as .csv.

当用户:<

When the user:


  1. 在框中写入子名称

  2. 按下获取数据按钮

发生什么:


  1. 它创建了一个test.csv(保存在项目的根目录中)

  2. 使用Praw检索数据

  3. 数据被插入进入.csv

  4. 数据被呈现给用户查看

  1. it's created a test.csv (saved in the root of the project)
  2. data is retrieved using Praw
  3. data is inserted into the .csv
  4. data is rendered for the users to see

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

The problem now is: I want the button with 'Export to Excel', to download the generated file from the root of the Django project.

这是按钮:

 <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:

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

Question is: How can I make the user export the file using the button? What am I doing wrong?

提前感谢您的帮助/指导

Thanks in advance for your help / guidance

方便的链接:

链接1

链接2

链接3

链接4

推荐答案

您必须先创建 response 对象,以分配头文件。

You must first create the response object in order to assign headers to it.

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

取自此处

这篇关于使用按钮从Django Project root下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆