• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

1.5K
Views
Cómo guardar io.BytesIO pdfrw PDF en Django FileField

Lo que estoy tratando de hacer es básicamente:

  1. Obtener PDF desde URL
  2. Modificarlo a través de pdfrw
  3. Guárdelo en la memoria como un BytesIO obj
  4. Cárguelo en Django FileField a través Model.objects.create(form=pdf_file, name="Some name")

Mi problema es que cuando se ejecuta el método create() , guarda todos los campos excepto el form .

ayudantes.py

 import io import tempfile from contextlib import contextmanager import 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.name def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict): template_pdf = pdfrw.PdfReader(input_pdf_path) ## PDF is modified here buf = io.BytesIO() print(buf.getbuffer().nbytes). # Prints "0"! pdfrw.PdfWriter().write(buf, template_pdf) buf.seek(0) return buf

vistas.py

 from django.core.files import File class 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', {})

Como puede ver, print() da dos valores diferentes a medida que se completa el BytesIO, lo que me lleva a creer que el aumento en el tamaño significa que en realidad hay datos en él. ¿Hay alguna razón por la que no se guarde correctamente en mi instancia de modelo Django? Además, si alguien conoce una forma más eficiente de hacer esto, ¡hágamelo saber!

over 3 years ago · Santiago Trujillo
2 answers
Answer question

0

Aquí está la documentación sobre cómo guardar un archivo en un objeto .

 from django.core.files import File filled_pdf = FilledPDF() filled_pdf.form.save('test_pdf.pdf', File(submitted_form.getvalue()), save=True)
over 3 years ago · Santiago Trujillo Report

0

Puede usar la clase ContentFile en su código. Hice la modificación en consecuencia en su opinión para guardar su archivo en el campo de archivo.

 from django.core.files.base import ContentFile class 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"}) pdf_content = ContentFile(submitted_form.getvalue(), 'sample.pdf') FilledPDF.objects.create(form=pdf_content, name="Test PDF") return render(request, 'index.html', {})

También puede usar el método de save para almacenar archivos usando la clase ContentFile .

 from django.core.files.base import ContentFile class 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"}) pdf_content = ContentFile(submitted_form.getvalue()) filled_pdf = FilledPDF() filled_pdf.name = "Test PDF" filled_pdf.form.save("sample.pdf", pdf_content, save=False) filled_pdf.save() return render(request, 'index.html', {})
over 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error