【问题标题】:Django - have created a pdf file using ReportLab but how do i store it into a FileField record?Django - 使用 ReportLab 创建了一个 pdf 文件,但我如何将它存储到 FileField 记录中?
【发布时间】:2020-10-12 03:34:40
【问题描述】:

在views.py中:

        c = canvas.Canvas(str(num)+'.pdf')
        c.setPageSize((page_width, page_height))
        c.drawInlineImage('logo.jpg', margin, page_height - image_height - margin,
                          image_width, image_height)
        c.setFont('Arial', 80)
        text = 'INVOICE'
        c.save()
        tt2 = Invoices_list.objects.all().filter(Number=num)
        tt2.update(document=c)

在models.py中:

class Invoices(models.Model):
    Date = models.DateTimeField()
    Name = models.CharField(max_length=100, blank=True, null=True)
    document = models.FileField(upload_to='temp/', blank=True, null=True)

我的视图创建了一条记录并完成了日期和名称记录,然后我创建了工作正常的 pdf(可以在我的根目录中看到它)但是我如何将它作为 tt2.update(document =c) 生成文件名“ 而不是 333.pdf(其中 num=333),尽管 333.pdf 位于我的 django 项目的根目录中。我如何从我的根进入 FileField 记录,下一个问题是我使用 Heroku 托管,所以不确定这是否会导致其他问题。 提前致谢

任何

【问题讨论】:

    标签: django pdf reportlab filefield


    【解决方案1】:

    您必须导入您的模型,然后在视图中创建一个新对象以填充您的数据库(如果这是您对 send it to the FileField 的意思),如下所示:

    Views.py

    from your_app.models import Invoices
    
    c = canvas.Canvas(str(num)+'.pdf')
            c.setPageSize((page_width, page_height))
            c.drawInlineImage('logo.jpg', margin, page_height - image_height - margin,
                              image_width, image_height)
            c.setFont('Arial', 80)
            text = 'INVOICE'
            c.save()
    
    obj, created = Invoices.objects.update_or_create(
                                    defaults={
                                        'document': c,                                    
                                    }
    )
    

    更新:

    请在您的模型中包含一个文档检查,如下所示:

    
    class Invoices(models.Model):
        Date = models.DateTimeField()
        Name = models.CharField(max_length=100, blank=True, null=True)
        document = models.FileField(
            upload_to='temp/',
            blank=True,
            null=True,
            content_types = ['application/pdf'])
    

    【讨论】:

    • 尝试了上述但得到错误:“画布”对象没有属性“_committed”。我已经使用“tt2 = Invoices_list.objects.all().filter(Number=num)”导入了我的模型并尝试了“tt2.document = c”和“tt2.save()”,但也出现错误
    • 我也按照您的建议“tt2.update(document=c)”做了类似的事情,它没有错误地通过,但是当我查看我的文件时,文件名是“reportlab.pdfgen.canvas。位于 0x000001CDF2F87CA0" 的画布对象(而不是 num=333 的 "333.pdf")并且不打开我的文件。感谢您的帮助
    • 编辑了我的帖子。您还可以在创建 pdf 后分享 print(c) 吗?
    • print(c) 显示
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2020-05-27
    • 2011-11-22
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多