簡體   English   中英

使用 FileField 包裝器和內存文件創建 Django object?

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

我正在嘗試在我的應用程序中構建一個功能,其中將創建一個內存 PDF 文件,並且該文件將保存在我的Document FileField的 FileField 中。

流程說明:


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 

要保存上面創建的文件,我們可以執行以下操作

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

上面的代碼在終端中運行良好,但由於我無法在我的 Django 應用程序中創建本地副本,我必須做這樣的事情來保存文件

from django.core.files import File

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

文件包裝器接受 python 文件 object 但上述代碼仍然不起作用。

執行后在我的 Django Admin 中沒有創建文件

如果您需要更多信息,請發表評論。

如果要將生成的文件保存到 model 字段中,則應將其保存在媒體目錄中,並且可以通過路徑保存文件:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM