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

Aru*_*man 3 python pdf django file django-models

我现在正在尝试将使用 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
Run Code Online (Sandbox Code Playgroud)

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

her*_*ert 7

如果您查看API 文档文档

\n\n
\n

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

\n
\n\n
from django.core.files import File\n# Open an existing file using Python\'s built-in open()\nf = open(\'/path/to/hello.world\')\nmyfile = File(f)\n
Run Code Online (Sandbox Code Playgroud)\n\n

所以 ifpdf是一个字符串,你可以使用:

\n\n
from django.core.files.base import ContentFile\nmyfile = ContentFile(pdf)\ninstance.structural_info.save(\'structure.pdf\', myfile)\n
Run Code Online (Sandbox Code Playgroud)\n