Vivek K. Singh
Vivek K. Singh

Reputation: 170

create Django object with FileField using `File` wrapper and in-memory-file?

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.

Upvotes: 0

Views: 636

Answers (1)

Mukhtor Rasulov
Mukhtor Rasulov

Reputation: 587

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()

Upvotes: 1

Related Questions