Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a StringIO like class, that extends django.core.files.File

Tags:

python

django

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

like image 983
joozek Avatar asked Jul 25 '10 19:07

joozek


People also ask

What is BytesIO in Django?

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.

What is Django ContentFile?

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

How can I get image name in Django?

You can obtain such name with os. path. splitext [Python-doc] to split a filename in the "root" and the "extension".


1 Answers

You can use ContentFile instead of File

from django.core.files.base import ContentFile

photo.image.save(name, ContentFile(buffer))
like image 112
Jason Avatar answered Sep 21 '22 06:09

Jason