我有一个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'属性的对象(文件是文件上载字段)。如果我只是返回对象,那么我的浏览器会正确下载文件,因此文件正常。
答案 0 :(得分: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('/')