38š
-
models.FileField
(models.ImageField
) needsdjango.core.files.base.File
like objects
ex)django.core.files.base.File
django.core.files.images.ImageFile
-
File
orImageFile
needs two args.-
IO object : which has
seek()
method (ex)io.BytesIO
). -
name :
str
. (important! without name, it will not work).
-
-
bytes object doesnāt have IOās methods(ex)
seek()
). it should be converted to IO object.
models.py
class Message(models.Model):
image = models.ImageField(upload_to='message_image/%Y/%m', null=True)
views.py or consumers.py or some-where.py
import io
from django.core.files.images import ImageFile
from myapp.models import Message
def create_image_message(image_bytes):
image = ImageFile(io.BytesIO(image_bytes), name='foo.jpg') # << the answer!
new_message = Message.objects.create(image=image)
š¤kochul
9š
You can try:
from django.core.files.base import ContentFile
import base64
file_data = ContentFile(base64.b64decode(fileData))
object.file.save(file_name, file_data)
You can use your file_name with an .m3u extension, and you shall have it.
š¤Navid Khan
- [Django]-Why there are two process when i run python manage.py runserver
- [Django]-Django AutoField with primary_key vs default pk
- [Django]-How to test "render to template" functions in django? (TDD)
1š
I solved using temporary file. I used this code:
extM3u = str.encode(body.decode('utf8').split('EXTM3U\n#')[1].split('------WebKitFormBoundary')[0])
fileTemp = NamedTemporaryFile(delete=True, dir='media/tmp')
fileTemp.write(extM3u)
filenameRe = re.compile('.*?filename=[\'"](.*?)[\'"]')
filename = regParse(filenameRe, body.decode('utf8'))
file = File(fileTemp, name=filename)
m3u = M3u(titleField=filename, fileField=file)
m3u.save()
š¤ocram88
- [Django]-How about having a SingletonModel in Django?
- [Django]-Django F() division ā How to avoid rounding off
- [Django]-PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django
1š
You can use a ContentFile
. To do so:
from django.core.files.base import ContentFile
content_file = ContentFile(file_bytes, name=file_name)
# Assumes MyModel has a FileField called `file`
MyModel.objects.create(file=content_file)
š¤Zags
- [Django]-Django QuerySet order
- [Django]-Django 1.7 ā App 'your_app_name' does not have migrations
- [Django]-How to assign items inside a Model object with Django?
-1š
convert string to bytes
bytes_data = ... # bytes
string_data = bytes_data.hex() # this is a string that you can save in TextField in django model
then, to get bytes from the string:
bytes_data_2 = bytes.fromhex(string_data)
I apologize for the crooked translation, Iām still only learning English.
- [Django]-Filtering dropdown values in django admin
- [Django]-Extend base.html problem
- [Django]-Django :How to integrate Django Rest framework in an existing application?
Source:stackexchange.com