Gaven
Gaven

Reputation: 1087

Django download csv from model database

I don't know why this is so difficult but I want to download a CSV file that has already been saved to my database for users to look at on their own PCs. Here are my models and views:

models.py

class datasheet(models.Model):
    file_name = models.FileField(upload_to = 'upload', max_length = 100)

    def __str__(self):
        return 'File id: {}'.format(self.id)

views.py

def download(request):
    csvfile = datasheet.objects.get(id = 1)
    return (csvfile as a downloaded attachment)

Any ideas?

Upvotes: 0

Views: 709

Answers (3)

NKSM
NKSM

Reputation: 5854

You can add "download" attribute inside your tag to download files.

<a download href="{{ datasheet.file_name.url }}">{{ datasheet.file_name }}</a>

Or FileResponse is a subclass of StreamingHttpResponse optimized for binary files.

import os

from django.http import FileResponse

def download(request):
    csvfile = datasheet.objects.get(id=1)
    fullpath = csvfile.file_name.path
    if not os.path.exists(fullpath):
        raise Http404('{0} does not exist'.format(fullpath))

    return FileResponse(
        open(fullpath, 'rb'), as_attachment=True,
        filename=csvfile.file_name.name)

Upvotes: 0

wiltonsr
wiltonsr

Reputation: 1027

Based on docs

import os
from django.http import HttpResponse, Http404

def download(request):
    csvfile = datasheet.objects.get(id = 1)
    if os.path.exists(csvfile.file_name.path):
        with open(csvfile.file_name.path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="text/csv")
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(csvfile.file_name.path)
            return response
    raise Http404

Upvotes: 1

mahyard
mahyard

Reputation: 1248

nothing you need except, opening the file and returning it as an attachment file to the response object.

from django.http import HttpResponse, HttpResponseNotFound


file_location = 'upload/'+csvfile

with open(file_location, 'r') as f:
   file_data = f.read()

# sending response 
response = HttpResponse(file_data, content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="{}"'.format(csvfile)

return response

Upvotes: 0

Related Questions