【问题标题】:How to add PDF file created with BytesIO into a FileField in a model of Django如何将使用 BytesIO 创建的 PDF 文件添加到 Django 模型中的 FileField
【发布时间】:2021-10-19 07:39:41
【问题描述】:

我可以在 Django 应用程序中使用 reportlab 创建 PDF 文件。但是,我无法将它添加到模型中的 FileField 中。我想知道如何将 io.BytesIO 数据传输到 Django 中的 FileField。

这是我的views.py的总结。

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
from reportlab.pdfbase import pdfmetrics

buffer = io.BytesIO()
cc = canvas.Canvas(buffer, pagesize=A4)

# describe something
font_name = "HeiseiKakuGo-W5"
cc.registerFont(UnicodeCIDFont(font_name))
cc.setFont(font_name, 7)
cc.drawString(65*mm, 11*mm, 'test')

cc.showPage()
cc.save()
buffer.seek(0)

exampleObject= get_object_or_404(SomeModel, pk=self.kwargs['pk'])
exampleObject.exampleFileField.save('test.pdf', File(buffer)) # here! this sentence doesn't work.
exampleObject.save()

return FileResponse(buffer, as_attachment=True, filename='test.pdf')

关键是下面的句子不起作用。我认为“文件(缓冲区)”不合适。

exampleObject.exampleFileField.save('test.pdf', File(buffer))

虽然有一次我尝试在目录中创建 pdf 文件作为临时文件后将 pdf 保存到 FileField 中,但我更喜欢使用 io.BytesIO。

【问题讨论】:

    标签: python django pdf reportlab bytesio


    【解决方案1】:

    我相信你失踪了buffer.get_value()

    我也使用ContentFile 而不是File,但不确定是否有必要。

    我刚刚测试了以下 sn-p,它可以使用 reportlab==3.5.32

    import io
    
    from django.core.files.base import ContentFile
    from reportlab.lib.pagesizes import A4
    from reportlab.pdfgen import canvas
    
    from my_app.models import MyModel
    
    buffer = io.BytesIO()
    canv = canvas.Canvas(buffer, pagesize=A4)
    canv.drawString(100, 400, "test")
    canv.save()
    pdf = buffer.getvalue()
    buffer.close()
    
    my_object = MyModel.objects.latest("id")
    my_object.file_field.save("test.pdf", ContentFile(pdf))
    
    

    【讨论】:

    • 非常感谢!这很好用。这是我关于堆栈溢出的第一篇文章。从您的帖子中,我还学会了如何总结我的代码以便在这里发布问题。
    【解决方案2】:

    您可能需要在您的buffer 上添加seek(0),因为它之前已经使用过,我不会感到惊讶缓冲区会在最后并导致在 Django 中保存一个空文件。

    【讨论】:

    • 感谢您的评论!!对不起,我做了一个错误的总结。在我的实际应用中,描述了“buffer.seek(0)”。我的应用程序可以创建一个 pdf 文件。但是,它不能将 pdf 文件保存到 FileField 中。
    猜你喜欢
    • 2011-11-22
    • 2013-06-01
    • 1970-01-01
    • 2020-10-12
    • 2011-07-18
    • 2019-07-23
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    相关资源
    最近更新 更多