0
我试图生成一个PDF文件,并将其添加到Django FileField
。没有什么幻想,但我似乎无法得到我将生成的PDF添加到FileField失败;添加本地PDF工程
当使用我的硬盘驱动器上的本地文件,一切工作正常:
>>> 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试图同时,事情不要” t工作:
>>> 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
对象被接受,另一个不是?
谢谢,这有帮助。缺少的是我还需要通过'invoice.pdf.name'为存储提供一个文件名,否则不会发生实际的'save()'。我已经调整了你的答案。 – SaeX