Is it possible in Django to save a pdf from a view to a model (while downloading it at the same time)?
So far, these steps work already:
What dows not work:
My code:
Models
from django.db import models
class TestModel(models.Model):
def pdf_upload_path(instance, filename):
return f'utility_bills/{instance.created_date.strftime("%Y-%m-%d")}_test_{filename}'
created_date = models.DateTimeField(
auto_now=False,
auto_now_add=True,
null=True,
blank=True,
)
pdf = models.FileField(upload_to=pdf_upload_path, blank=True)
Views
import io
from django.core.files.base import ContentFile
from django.http import FileResponse
from reportlab.platypus import SimpleDocTemplate, Paragraph
from .models import (TestModel)
## Create PDF ##
def utility_pdf(request):
# General Setup
pdf_buffer = io.BytesIO()
my_doc = SimpleDocTemplate(pdf_buffer)
sample_style_sheet = getSampleStyleSheet()
# Instantiate flowables
flowables = []
test = Paragraph("Test", sample_style_sheet['BodyText'])
# Append flowables and build doc
flowables.append(test)
my_doc.build(flowables)
# create and save pdf
pdf_buffer.seek(0)
pdf = pdf_buffer.getvalue()
file_data = ContentFile(pdf)
pdf = TestModel(pdf=file_data)
pdf.save()
response = FileResponse(pdf_buffer, filename="some_file.pdf")
return response
Template *
It is probably worth mentioning, that I don't get the data for the pdf from a form, but from the session of a previous page:
{% extends 'core/base.html' %}
<!-- Title -->
{% block title %} Test Statement {% endblock %}
<!-- Body -->
{% block content %}
<div class="container test-submit-last">
<form>
<div class="col">
<a class="btn btn-primary" href="{% url 'test_pdf'%}" target="_blank" role="button">Show PDF</a>
</div>
</div>
</form>
</div>
{% endblock %}
I found it! 😀
All I had to do is give my pdf a name - and now it works!
pdf_data = pdf_buffer.getvalue()
file_data = ContentFile(pdf_data)
## Here is the crucial part that was missing: ##
file_data.name = 'test.pdf'
pdf = UtilityBill(lease=pdf_lease, pdf=file_data)
pdf.save()
response = FileResponse(pdf_buffer, filename="some_file.pdf")