django - 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 托管,所以不确定这是否会导致其他问题。提前致谢
任何
解决方案
您必须导入您的模型,然后在您的视图中创建一个新对象来填充您的数据库(如果这是您的意思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'])
推荐阅读
- python - AIRFLOW : 自定义 SFTPOperator 以下载多个文件
- architecture - 带有计划任务的可扩展中间件?
- gitlab-ci - 如何向 .gitlab-ci.yaml 文件添加注释?
- python - 当我猜不透时,我正在尝试重玩游戏(当我猜不透或找到正确答案时再玩)
- design-patterns - Azure 函数 - 使用什么聚合模式?
- node.js - 时刻获取日期数组中的下一个日期
- ruby-on-rails - Rails 仍然从 Heroku 提供资产,而不是使用 Cloudfront
- reactjs - ReactJS Material UI:使用 @keyframes 为 svg 设置动画
- google-analytics - 分析中心报告 pdf 导出不起作用
- dataframe - PySpark 重新分配重复行的值