将渲染的pdf文件保存到模型字段Django [英] Saving a rendered pdf file to model field Django

查看:96
本文介绍了将渲染的pdf文件保存到模型字段Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将使用HTML呈现的pdf文件保存到模型字段中,这会引发此错误。

I'm trying to save a pdf file which is rendered using HTML to a model field right now, it throws this error.

强制转换为Unicode:需要字符串或缓冲区,已找到实例

coercing to Unicode: need string or buffer, instance found

这是代码

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

structural_info是文件字段。
正确的做法是什么?

structural_info is the file field. What is the correct way to do it?

推荐答案

如果您查看 API文档文档


请注意,content参数应该是
django.core.files.File的实例,而不是Python的内置文件对象。您可以
像这样从现有的Python文件对象中构造文件

Note that the content argument should be an instance of django.core.files.File, not Python’s built-in file object. You can construct a File from an existing Python file object like this



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)

因此,如果 pdf 是字符串您可以使用:

so if pdf is a string you could use:

from django.core.files.base import ContentFile
myfile = ContentFile(pdf)
instance.structural_info.save('structure.pdf', myfile)

这篇关于将渲染的pdf文件保存到模型字段Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆