Django Weasyprint PDF output into Postgres Database

67 Views Asked by At

I am trying to stick a WeasyPrint html PDF into the Model. Using Django.

I can generate the PDF file fine.

pdf_file = HTML(string=html,base_url=base_url).write_pdf(stylesheets, [css_path],font_config=font_config)

Now what is best way to convert the pdf_file output to a format I can use for the database?

class Reports(models.Model):

    pdf = models.FileField( upload_to='media/pdfs/', max_length=254, )

    created = models.DateField(auto_now=False, auto_now_add=True)

If I do something like this it creates the file automatically before the Model.

    fs = FileSystemStorage()
    report = fs.save(f'pdfs/{uuid}.pdf', File(BytesIO(pdf_file)) )

And gives the table a 'pdf/...' in the database.

What is most efficent way to convert the Wesasy HTML into a format the Model can use and let the model save the file?

Thanks.

1

There are 1 best solutions below

2
mariodev On

You can do it in two steps:

  1. create the object without the file assigned (making sure that file field is nullable, you can handle validation separately if needed).
  2. Use save method on the file field to save the pdf

Here's how you can do it:

import io
from django.core.files.base import ContentFile, File

res = io.BytesIO()
HTML(string=html).write_pdf(res)
pdf = ContentFile(res.getvalue())

report = Reports.objects.create(
    ...
)
report.file.save(filename, File(pdf))

filename is the file name you can generate however