Download file from Django Project root using a but

2019-07-29 06:39发布

问题:

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