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