简体   繁体   English

将渲染的pdf文件保存到模型字段Django

[英]Saving a rendered pdf file to model field Django

I'm trying to save a pdf file which is rendered using HTML to a model field right now, it throws this error. 我正在尝试将使用HTML呈现的pdf文件保存到模型字段中,这会引发此错误。

coercing to Unicode: need string or buffer, instance found 强制转换为Unicode:需要字符串或缓冲区,找到实例

this is the code 这是代码

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 is the file field. structural_info是文件字段。 What is the correct way to do it? 正确的方法是什么?

If you look at the API Documentation documentation : 如果您查看API文档文档

Note that the content argument should be an instance of django.core.files.File, not Python's built-in file object. 请注意,content参数应该是django.core.files.File的实例,而不是Python的内置文件对象。 You can construct a File from an existing Python file object like this 您可以像这样从现有的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 is a string you could use: 因此,如果pdf是字符串,则可以使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM