我现在正在尝试将使用 HTML 呈现的 pdf 文件保存到模型字段,它会抛出此错误。
强制转换为 Unicode:需要字符串或缓冲区,已找到实例
这是代码
def save_to_pdf(template_src, context_dict, pk):
import ipdb; ipdb.set_trace()
instance = get_object_or_404(
Project.objects.filter(pk=pk, is_deleted=False))
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result,link_callback=fetch_resources)
pdfnew=file(pdf)
instance.structural_info.save('structure.pdf',pdfnew)
return True
Structured_info 是文件字段。
正确的做法是什么?
如果你看一下API 文档 文档 https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.fields.files.FieldFile.save:
请注意,内容参数应该是一个实例
django.core.files.File,不是Python的内置文件对象。你可以
从现有的 Python 文件对象构造一个文件,如下所示
from django.core.files import File
# Open an existing file using Python's built-in open()
f = open('/path/to/hello.world')
myfile = File(f)
so if pdf
是一个你可以使用的字符串:
from django.core.files.base import ContentFile
myfile = ContentFile(pdf)
instance.structural_info.save('structure.pdf', myfile)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)