title: Django: save pdf from view to model (reportlab)
body: <p>Is it possible in <strong>Django</strong> to save a <strong>pdf</strong> from a <strong>view</strong> to a <strong>model</strong> (while downloading it at the same time)?</p>
  <hr />
  <p><em>So far, these steps work already:</em></p>
  <ul>
  <li>the pdf is displayed in a new tab and I can download it</li>
  <li>the model instance is created (but empty)</li>
  </ul>
  <hr />
  <p><em>What dows not work:</em></p>
  <ul>
  <li>the created model instances does not have a file path and there is no PDF file saved anywhere on the server</li>
  </ul>
  <hr />
  <p><em>My code:</em></p>
  <p><strong>Models</strong></p>
  <pre><code>from django.db import models
  class TestModel(models.Model):
      
      def pdf_upload_path(instance, filename):
          return f'utility_bills/{instance.created_date.strftime(&quot;%Y-%m-%d&quot;)}_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)
  </code></pre>
  <p><strong>Views</strong></p>
  <pre><code>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(&quot;Test&quot;, 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=&quot;some_file.pdf&quot;)
      
      return response
  </code></pre>
  <p><strong>Template</strong> *</p>
  <p><em>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:</em></p>
  <pre><code>    {% extends 'core/base.html' %}
      
      &lt;!-- Title --&gt;
      {% block title %} Test Statement {% endblock %}
      
      &lt;!-- Body --&gt;
      {% block content %}
      
      &lt;div class=&quot;container test-submit-last&quot;&gt;
          &lt;form&gt;
                  &lt;div class=&quot;col&quot;&gt;
                      &lt;a class=&quot;btn btn-primary&quot; href=&quot;{% url 'test_pdf'%}&quot; target=&quot;_blank&quot; role=&quot;button&quot;&gt;Show PDF&lt;/a&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
          &lt;/form&gt;
      &lt;/div&gt;
  
  
  {% endblock %}
  </code></pre>