Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: how save bytes object to models.FileField?

Tags:

python

django

My web application has the following structure:

  1. backend with Django
  2. frontend with React.

I have a form with React. I send a file from client form and I receive the file in my Django application with an APIView.

I receive a m3u file as bytes object.

b'------WebKitFormBoundaryIaAPDyj9Qrx8DrWA\r\nContent-Disposition: 
form-data; name="upload"; 
filename="test.m3u"\r\nContent-Type: audio/x- 
mpegurl\r\n\r\n#EXTM3U\n#EXTINF:-1 tvg-ID="" tvg-name="...

I would save the file in a Django model to a models.FileField and convert bytes object to m3u file. How you do it?

like image 698
ocram88 Avatar asked Dec 25 '18 20:12

ocram88


2 Answers

  1. models.FileField(models.ImageField) needs django.core.files.base.File like objects ex)

    • django.core.files.images.ImageFile

    • django.core.files.base.ContentFile

  2. ImageFile or ContentFile needs two args.

    1. IO object : which has seek() method (ex) io.BytesIO).

    2. name : str. (important! without name, it will not works).

  3. 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)
like image 132
kochul Avatar answered Sep 21 '22 10:09

kochul


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.

like image 29
Navid Khan Avatar answered Sep 21 '22 10:09

Navid Khan