简体   繁体   中英

Django: save pdf from view to model (reportlab)

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:

  • the pdf is displayed in a new tab and I can download it
  • the model instance is created (but empty)

What dows not work:

  • the created model instances does not have a file path and there is no PDF file saved anywhere on the server

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM