首页 > 解决方案 > 从响应中获取空文件并且无法将文件保存在 django 模型类中

问题描述

我的任务是创建.xlsx迟到员工的文件并将其返回下载,同时我应该为每天创建一个带有字段daylist( .xlsx) 的对象。我的实现代码是:

...
    file = excel_file.save('my_data.xlsx')

    day = Day.objects.create(days_date=timezone.now(), days_file=File(file))

    response = HttpResponse(file, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',)
    response['Content-Disposition'] = 'attachment; filename={date}-attendance.xlsx'.format(date=timezone.now().strftime('%Y-%m-%d'),)

    return response

没有错误消息,但来自的文件response为空,因为类对象不存在

我的models.py

class Day(models.Model):
    days_date = models.DateField()
    days_file = models.FileField(upload_to='day/')

    def __str__(self):
        return '{date}'.format(date=timezone.now().strftime('%Y-%m-%d'))

我正在使用django==2.2 openpyxl,我正在使用Linux ubuntu OS

标签: pythondjango

解决方案


基本上,您应该将文件作为stram以便能够将其作为 django响应传递;如文档中所述,您应该在您的views.py

from tempfile import NamedTemporaryFile
from openpyxl import Workbook

    #...
    with NamedTemporaryFile() as tmp:
        file = excel_file.save(tmp.name)
        tmp.seek(0)
        stream = tmp.read()

        day = Day.objects.create(days_date=timezone.now(), days_file=File(file))
        response = HttpResponse(stream, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',)
        response['Content-Disposition'] = 'attachment; filename={date}-attendance.xlsx'.format(date=timezone.now().strftime('%Y-%m-%d'),)

        return response

推荐阅读