1

I want to let the user submit a form with some filter criteria and respond with a csv file. This is my code:

template:

<form action="{% url 'filter_tracks' %}" method="get" id="filter-form">
    <various filter params>
    ...
    <a class="md-btn"  href="javascript:void(0)" onclick="$('#filter-form').submit();" id="csv_btn">Export</a>
</form>

views.py

filename = "TRACKS_EXP{x}_{z}.csv".format(x=int(time.time()), z=lang)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="{x}"'.format(x=filename)
response.write(u'\ufeff'.encode('utf8'))
writer = csv.writer(response, delimiter=',', dialect='excel', quotechar = "\"", lineterminator='\r\n',)
for track in track_list:
    writer.writerow([...])

return response

Although it works,

I get the data inside my HTML page and not in a downloadable file.

What am I doing wrong?

1 Answer 1

1

This is something i do to send a file from django to client, This should work in your case too

import os
from django.conf import settings
from django.http import HttpResponse

def download(request, path):
    file_path = os.path.join(settings.MEDIA_ROOT, path)
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
            return response
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.