Home > Software design >  Downloading an Excel File in a Django View
Downloading an Excel File in a Django View

Time:09-29

I have included an excel file in my project directory. I want to created a Django view that allows a user to download that file. Please how best do I handle that?

CodePudding user response:

import csv
from django.http import StreamingHttpResponse
# create an echo handler, returns what is put into for the writer
psuedo_buffer = Echo()
#Build csv writer ontop of echo filelike instance
writer = csv.writer(psuedo_buffer)
#Stream the response row by row using the psuedo_writer
response = StreamingHttpResponse((
    writer.writerow(row) for row in query_data),
    content_type="text/csv"
)
response['Content-Disposition'] = 'attachment; filename="Something.csv"'
return response

This is a code snippet that I use to return a streaming HTTP response with the data. The data that would be in query_data can either be raw CSV data from a file handler which you can pretty easily find a few ways to open the data and drop it into this function, or you can use arrays of data from query sets to pass in. Just format your data for query_set and return this Response handler in either API views or Template views. Hope this helps!

Data should be formatted in arrays of data, which you can use .dict to get parsable data from most models or simply parsing the csv into memory with the CSV library will accomplish the same thing.

CodePudding user response:

Is your file associated with a Model? I prefer to create a Model to store general resources.

models.py

class Resources(models.Model):
    description = models.CharField(max_length=200)
    file = models.FileField(upload_to='uploads/resources/')

    def __str__(self):
        return self.description  

views.py

...
some_file = Resources.objects.get(description='Your description')
...

return render(request, "template.html", {
    "some_file": some_file,
}

template.html

...
    <p>Download <a href="{{ some_file.file.url }}" target="_blank">file.</a></p>
...
  • Related