Download file from Django Project root using a button

假装没事ソ 提交于 2019-12-13 17:19:32

问题


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

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

When the user:

  1. writes a subreddit name in the box
  2. presses the button 'Get Data'

What happens:

  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

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

This is for the 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> 

This is in 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

This is in 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

Handy links:

Link 1

Link 2

Link 3

Link 4


回答1:


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

Taken from here



来源:https://stackoverflow.com/questions/42671585/download-file-from-django-project-root-using-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!