将生成的PDF添加到FileField失败;添加本地PDF工作

时间:2016-07-22 21:48:22

标签: python django

我正在尝试生成PDF文件并将其添加到Django FileField。没什么好看的,但我似乎无法得到我

在我的硬盘上使用本地文件时,一切正常:

>>> invoice = Invoice.objects.get(pk=153)
>>> local_file = open('my.pdf')
>>> djangofile = File(local_file)
>>> type(local_file)
<type 'file'>
>>> type(djangofile)
<class 'django.core.files.base.File'>
>>> invoice.pdf = djangofile
>>> invoice.pdf
<FieldFile: my.pdf>
>>> invoice.save()
>>> invoice.pdf
<FieldFile: documents/invoices/2016/07/my.pdf>

然而,当使用生成的PDF尝试相同时,事情不起作用:

>>> invoice = Invoice.objects.get(pk=154)
>>> html_template = get_template('invoicing/invoice_pdf.html')
>>> rendered_html = html_template.render({'invoice': invoice}).encode(encoding="UTF-8")
>>> pdf_file = HTML(string=rendered_html).write_pdf()
>>> type(pdf_file)
<type 'str'>
>>> djangofile = File(pdf_file)
>>> type(djangofile)
<class 'django.core.files.base.File'>
>>> invoice.pdf = djangofile
>>> invoice.pdf
<FieldFile: None>
>>> invoice.save()
>>> invoice.pdf
<FieldFile: None>

我做错了什么?为什么一个django.core.files.base.File对象被接受而另一个不是?

1 个答案:

答案 0 :(得分:1)

File()只是Python文件对象的包装器。它不适用于生成的PDF这样的字符串。为此,您需要ContentFile class。尝试:

(...)
djangofile = ContentFile(pdf_file)
invoice.pdf = djangofile
invoice.pdf.name = "myfilename.pdf"
invoice.save()