如何保存一个Excel文件并将其附加到新的对象?

我有一个Django的项目,我用xlwt(文件生成的最后一段)创build了一个excel文件。

export_wb.save(output) output.seek(0) response = HttpResponse(output.getvalue()) response['Content-Type'] = 'application/vnd.ms-excel' response['Content-Disposition'] = 'attachment; filename='+filename return response 

现在在我看来,我想生成这个文件,并将其附加到一个新的对象,并保存它,所以我有一个新的对象在pipe理与附加的Excel文件。 我正在尝试这样的事情

 def test(request): exported_ingredients = export(request, app_name='ingredients', model_name='ingredient') new_export = IngredientExportItem(file_name="x", slug="x", file=exported_ingredients) new_export.save() return HttpResponseRedirect('/') 

我不断收到此错误: 'HttpResponse' object has no attribute '_committed'

似乎不喜欢我设置为“文件”属性的对象(文件是一个file upload字段)。 如果我只是返回对象,然后我的浏览器正确下载文件,所以文件是确定的。

你的回应不是django文件对象,它是一个django HttpResponse对象。

如果你想从string中创build一个Django文件对象,请查看ContentFile 。

 from django.core.files.base import ContentFile def test(request): http_response = export(request, app_name='ingredients', model_name='ingredient') file_ = ContentFile(http_response.content) file_.name = http_response['Content-Disposition'].split('=')[-1] new_export = IngredientExportItem(file_name="x", slug="x", file=file_) new_export.save() return HttpResponseRedirect('/')