python - 从响应中获取空文件并且无法将文件保存在 django 模型类中
问题描述
我的任务是创建.xlsx
迟到员工的文件并将其返回下载,同时我应该为每天创建一个带有字段day
和list
( .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
解决方案
基本上,您应该将文件作为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
推荐阅读
- angular - Angular - 比较字符串
- python - TensorFlow 和 Keras 中的多重损失
- python - ValueError: int() 以 10 为底的无效文字:'Pending'
- chatbot - Botium 核心 - 频繁测试失败并显示消息“AllInstitutions_3/Line 7: error sent to bot Error”
- php - 我的 sql 插入查询没有错误,但没有向数据库中插入任何内容
- react-native - ScrollView 中包裹的多个 FlatList
- scala - 将列表的 spark DF 列拆分为单独的列
- python - 根据 xy 坐标计算行和列,TypeError: 'float' object is not subscriptable
- spring-boot - 来自 Google Kubernetes Engine 的邮件
- spring-boot - @Value("${server.address}") 返回 null