【问题标题】:Saving a rendered pdf file to model field Django将渲染的 pdf 文件保存到模型字段 Django
【发布时间】:2018-09-05 04:18:32
【问题描述】:

我现在正在尝试将使用 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

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

【问题讨论】:

    标签: python django file pdf django-models


    【解决方案1】:

    如果你看API Documentation documentation

    请注意,内容参数应该是 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)
    

    所以如果pdf 是你可以使用的字符串:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-02
      • 2020-05-07
      • 2012-10-27
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      相关资源
      最近更新 更多