0

I am trying to build a functionality in my application where an In-memory PDF file will be created and that file will get saved on a FileField in my Document model.

Explaination of the process:


from io import BytesIO
from PyPDF2 import PdfWriter

in_memory_file = BytesIO()
writer = PdfWriter()


writer.add_blank_page(height=200, width=200)
writer.write(in_memory_file)

# The contents of the `writer` got saved to the `io` file 

To save the above created file we can do the following

with open('new_local_file.pdf', 'wb') as local_file:
    local_file.write(in_memory_file.getbuffer())

The above code is working fine in terminal but since I cannot create local copies in my Django app, I have to do something like this to save the file

from django.core.files import File

obj = Document.objects.create(file_result=File(in_memory_file.getbuffer()))

The File wrapper accepts the python file object but still the above code is not working.

After execution no file is getting created in my Django Admin

Please comment if you need any more info.

1 Answer 1

1

If you want to save generated file to the model field you should save it in the media directory, And you can save the file by path:

from django.conf import settings


filename = "document.pdf"
directory = f"{settings.MEDIA_ROOT}/{filename}"
...
# in_memory_file generated here
...
with open(directory, 'wb') as local_file:
    local_file.write(in_memory_file.getbuffer())
obj = Document()
obj.file_result.name = filename
obj.save()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, but I wanted to ask if there is any other way where my memory-file converts directly to the FileField?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.