0

我正在尝试编写一个脚本,它将由 xhtml2pdf 创建的 pdf 直接保存到服务器,而不是按照通常的方式提示用户将其下载到他们的计算机上。Documents() 是我要保存到的模型,并且 new_project 和 output_filename 变量设置在其他地方。

            html = render_to_string(template, RequestContext(request, context)).encode('utf8')
            result = open(output_filename, "wb")
            pdf = CreatePDF(src=html, dest=results, path = "", encoding = 'UTF-8', link_callback=link_callback) #link callback was originally set to link_callback, defined below
            result.close()
            if not pdf.err:

                new_doc=Documents()
                new_doc.project=new_project
                new_doc.posted_by=old_mess[0].from_user_fk.username
                new_doc.documents = result
                new_doc.save()

使用此配置,当它到达 new_doc.save() 我得到错误:'file' object has no attribute '_committed'

有谁知道我该如何解决这个问题?谢谢!

4

1 回答 1

2

在玩弄它之后,我找到了一个可行的解决方案。问题是我没有在结果(pdf)仍然打开时创建新文档。

需要将“+”添加到 open() 以便 pdf 文件可用于读取和写入,而不仅仅是写入。

请注意,这确实首先将 pdf 保存在不同的文件夹(文件)中。如果这不是您的应用程序所需的结果,您将需要将其删除。

            html = render_to_string(template, RequestContext(request, context)).encode('utf8')
            results = StringIO()
            result = open("Files/"+output_filename, "w+b")
            pdf = CreatePDF(src=html, dest=results, path = "", encoding = 'UTF-8', link_callback=link_callback) #link callback was originally set to link_callback, defined below

            if not pdf.err:
                result.write(results.getvalue())
                new_doc=Documents()
                new_doc.project=new_project
                new_doc.documents.save(output_filename, File(result))
                new_doc.posted_by=old_mess[0].from_user_fk.username

                new_doc.save()
            result.close()
于 2014-07-24T16:44:24.063 回答