openpyxl保存到实例字段django

问题描述 投票:0回答:1

我想每次使用POST提交表单时插入一个Excel工作表文件。但是,必须在视图中及之后在视图中<,然后将其插入instance.field。型号:

class Order(models.Model): ... attachment = \ models.FileField(\ _("Sheet"), upload_to='uploads/', max_length=100, blank=True, null=True) ...

查看:

from openpyxl import Workbook from openpyxl.writer.excel import save_virtual_workbook class Order1(View): def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): obj = form.save(commit=False) #Creating sheet book = Workbook() sheet = book.active sheet['A1'] = 56 sheet['A2'] = 43 now = time.strftime("%x") sheet['A3'] = now #Calling model field instance - What im doing wrong here? obj.attachment = book.save("sample.xlsx") #Saving model instance obj.save() #Some return - required for AJAX return JsonResponse({"status": "OK"})

除附件字段外,全部保存。我在这里做错了什么?

我想每次使用POST提交表单时插入一个Excel工作表文件。但是,必须事先在视图中生成文件,然后再将其插入instance.field。型号:...

python django python-3.x openpyxl
1个回答
0
投票
您无法像这样直接保存文件。保存后,需要以二进制读取模式打开它,然后可以将其传递给File构造函数:
© www.soinside.com 2019 - 2024. All rights reserved.