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.