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

0 投票
1 回答
949 浏览
提问于 2025-04-17 10:28

我有一个django项目,我用xlwt创建了一个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

现在在我的视图中,我想生成这个文件,并把它附加到一个新对象上,然后保存这个对象,这样在管理后台就能看到带有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'属性的对象有问题(file是一个文件上传字段)。如果我只是返回这个对象,浏览器就能正确下载文件,所以文件本身是没问题的。

1 个回答

2

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

如果你想从字符串创建一个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('/')

撰写回答