Django:如何将字节对象保存到models.FileField?
我的Web应用程序具有以下结构:
My web application has the following structure:
- 使用Django的后端
- 使用React的前端.
我有一个与React的表格.我从客户端表单发送文件,并在我的Django应用程序中使用APIView接收文件.
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.
我收到一个m3u文件作为字节对象.
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="...
我会将Django模型中的文件保存到models.FileField并将bytes对象转换为m3u文件.你如何做到的?
I would save the file in a Django model to a models.FileField and convert bytes object to m3u file. How you do it?
-
models.FileField(models.ImageField)需要像对象一样的django.core.files.base.File例如)
models.FileField(models.ImageField) needs django.core.files.base.File like objects ex)
-
django.core.files.images.ImageFile
django.core.files.images.ImageFile
django.core.files.base.ContentFile
django.core.files.base.ContentFile
ImageFile或ContentFile需要两个参数.
ImageFile or ContentFile needs two args.
-
IO对象:具有seek()方法(例如io.BytesIO).
IO object : which has seek() method (ex) io.BytesIO).
name:str.(重要!没有名称,它将无法正常工作.)
name : str. (important! without name, it will not works).
bytes对象没有IO的方法(例如,seek()).应该将其转换为IO对象.
bytes object doesn't have IO's methods(ex) seek()). it should be converted to IO object.
models.py
models.py
class Message(models.Model):
image = models.ImageField(upload_to='message_image/%Y/%m', null=True)
views.py或consumers.py
views.py or consumers.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)