将生成的PDF添加到FileField失败;添加本地PDF有效

2024-04-25 23:14:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试生成一个PDF文件并将其添加到DjangoFileField。没什么特别的,但我好像搞不懂

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

>>> 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对象被接受而另一个不被接受?你知道吗


Tags: djangocorebasegetpdfmylocalhtml
1条回答
网友
1楼 · 发布于 2024-04-25 23:14:17

File()只是Python文件对象的包装器。它不能处理像生成的PDF那样的字符串。为此,您需要ContentFile class。尝试:

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

相关问题 更多 >

    热门问题