首页 > 解决方案 > Django - 使用 ReportLab 创建了一个 pdf 文件,但我如何将它存储到 FileField 记录中?

问题描述

在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)

在模型.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) 直接发送到 FileField生成文件名“<reportlab.pdfgen.canvas.Canvas object at 0x000001D51FB442E0> 而不是 333.pdf(其中 num=333)虽然 333.pdf 在我的 django 项目的根目录中。我如何将它从我的根目录复制到FileField 记录,下一个问题是我使用 Heroku 托管,所以不确定这是否会导致其他问题。提前致谢

任何

标签: djangopdfreportlabfilefield

解决方案


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

视图.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'])

推荐阅读