class MyModel(models.Model)
image = models.FileField(upload_to="blagh blagh...")
#more spam...
I have a file in memory and I want to save it via Django FileField save method, like this:
photo.image.save(name, buffer) # second arg should be django File
I've tried to use StringIO, but it doesn't extend django.core.files.File and thus doesn't implement method chunks(). I've wrapped it in a File object like that:
buffile = File(buffer, name) # first argument should be a file
photo.image.save(name, buffile)
But File methods use size and name fields of supplied file. StringIO doesn't define them. I've found this, but the link is dead
StringIO and BytesIO are methods that manipulate string and bytes data in memory. StringIO is used for string data and BytesIO is used for binary data. This classes create file like object that operate on string data. The StringIO and BytesIO classes are most useful in scenarios where you need to mimic a normal file.
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")
You can obtain such name with os. path. splitext [Python-doc] to split a filename in the "root" and the "extension".
You can use ContentFile instead of File
from django.core.files.base import ContentFile
photo.image.save(name, ContentFile(buffer))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With