django - 从 Django 中的 FileResponse 保存文件

如何从 Django 中的 FileResponse 将文件保存在 FileField 中。

我有最简单的 PDF 函数来在 Django 中创建 PDF 文件(根据 https://docs.djangoproject.com/en/4.0/howto/outputting-pdf/)。

import io
from django.http import FileResponse
from reportlab.pdfgen import canvas

def some_view(request):
    # Create a file-like buffer to receive PDF data.
    buffer = io.BytesIO()

    # Create the PDF object, using the buffer as its "file."
    p = canvas.Canvas(buffer)

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    p.drawString(100, 100, "Hello world.")

    # Close the PDF object cleanly, and we're done.
    p.showPage()
    p.save()

    # FileResponse sets the Content-Disposition header so that browsers
    # present the option to save the file.
    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename='hello.pdf')

它返回 PDF。但是如何将这个 PDF 保存在 FileField 中呢?

我需要这样的东西:

模型.py

class FileModel(models.Model):
    file = models.FileField()

视图.py

def some_view(request):
    [...same code as above to line buffer.seek(0)...]
    obj = FileModel()
    obj.file = FileResponse(buffer, as_attachment=True, filename='hello.pdf')
    obj.save()

回答1

对于这个任务,Django 提供了 https://docs.djangoproject.com/en/4.0/topics/files/#the-file-object

from django.core.files import File

def some_view(request):
    # ...same code as above to line buffer.seek(0)...
    obj = FileModel()
    obj.file = File(buffer, name='hello.pdf')
    obj.save()

相似文章