Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django从模型数据库下载csv_Python_Django - Fatal编程技术网

Python Django从模型数据库下载csv

Python Django从模型数据库下载csv,python,django,Python,Django,我不知道为什么这么难,但我想下载一个CSV文件,该文件已保存到我的数据库中,供用户在自己的电脑上查看。以下是我的模型和视图: 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) vie

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

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)
有什么想法吗?

您可以在标签中添加“下载”属性来下载文件

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

除了打开文件并将其作为附件文件返回到响应对象之外,您不需要其他任何东西

从django.http导入HttpResponse,HttpResponseNotFound
文件位置='upload/'+csvfile
打开(文件位置“r”)作为f:
file_data=f.read()
#发送响应
response=HttpResponse(文件\u数据,内容\u type='text/csv')
响应['Content-Disposition']='附件;filename=“{}”格式(csvfile)
返回响应
基于

导入操作系统
从django.http导入HttpResponse,Http404
def下载(请求):
csvfile=datasheet.objects.get(id=1)
如果os.path.exists(csvfile.file\u name.path):
打开(csvfile.file_name.path,'rb')作为fh:
response=HttpResponse(fh.read(),content_type=“text/csv”)
响应['Content-Disposition']='内联;filename='+os.path.basename(csvfile.file_name.path)
返回响应
提高Http404
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)