File Object in Django

File Object in Django

August 15, 2023 | django

Summary suspendedfc #

ref The File class is a thin wrapper around a Python file object () with some Django-specific additions. Internally, Django uses this class when it needs to represent a file. source

from django.core.files.base import File
stream = BytesIO() # stream or file like object
pdf_writer.write(stream)
page_obj.pdf.save(name=f"page_num.pdf",
                  content=File(stream))

File class #

source

  • The File class is a thin wrapper around a Python file object with some Django-specific additions. Internally, Django uses this class when it needs to represent a file.
  • The file attribute of the class refers to the underlying that this class wraps.

ContentFile class #

The ContentFile class inherits from File, but unlike File it operates on string content (bytes also supported), rather than an actual file. For example:

from django.core.files.base import ContentFile
f1 = ContentFile("esta frase está en español")
f2 = ContentFile(b"these are bytes")
 # or
fh = open(original_file_path, "r")
file_content = ContentFile(fh.read())

#or
ContentFile(b.getvalue())
b = io.BytesIO()
resized_photo.save(b, format=extension[1:])
default_storage.save(book.cover_photo.path, ContentFile(b.getvalue()))

ImageFile class #

source Django provides a built-in class specifically for images. django.core.files.images.ImageFile inherits all the attributes and methods of File, and additionally provides the following:

width #

Width of the image in pixels.

height #

Height of the image in pixels.

from a1.models import Model1
from django.core.files.images import ImageFile
m = Model1.objects.create()
stream = open("1.png", "rb") # from file system
m.f1 = ImageFile(stream)
m.save()


Go to random page

Previous Next