What I am trying to do is basically:
- Get PDF from URL
- Modify it via pdfrw
- Store it in memory as a BytesIO obj
- Upload it into a Django FileField via
Model.objects.create(form=pdf_file, name="Some name")
My issue is that when the create()
method runs, it saves all of the fields except for the form
.
helpers.py
import io
import tempfile
from contextlib import contextmanagerimport requests
import pdfrw@contextmanager
def as_file(url):with tempfile.NamedTemporaryFile(suffix='.pdf') as tfile:tfile.write(requests.get(url).content)tfile.flush()yield tfile.namedef write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):template_pdf = pdfrw.PdfReader(input_pdf_path)## PDF is modified herebuf = io.BytesIO()print(buf.getbuffer().nbytes). # Prints "0"!pdfrw.PdfWriter().write(buf, template_pdf)buf.seek(0)return buf
views.py
from django.core.files import Fileclass FormView(View):def get(self, request, *args, **kwargs):form_url = 'http://some-pdf-url.com'with as_file(form_url) as temp_form_path:submitted_form = write_fillable_pdf(temp_form_path, temp_form_path, {"name": "John Doe"})print(submitted_form.getbuffer().nbytes). # Prints "994782"!FilledPDF.objects.create(form=File(submitted_form), name="Test PDF") return render(request, 'index.html', {})
As you can see, print()
gives out two different values as the BytesIO is populated, leading me to believe the increase in size means there is actually data in it. Is there a reason it is not saving properly into my django model instance? Also, if anyone knows a more efficient way to do this, please let me know!