Django从model数据库下载csv文件



我不知道为什么这是如此困难,但我想下载一个CSV文件,已经保存到我的数据库中,供用户在自己的pc上查看。以下是我的模型和视图:

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)

任何想法?

基于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

您只需要打开文件并将其作为附件文件返回给响应对象。

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

可以添加"download"属性来下载文件。

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

FileResponseStreamingHttpResponse的子类,对二进制文件进行了优化。

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)

最新更新