Django 字段未保存

问题描述 投票:0回答:1

我想从客户端接收一个文件,并在将其保存到数据库之前对相应模型类中的图像进行一些处理。但是,由于直到 save() 方法结束时才保存文件,因此未创建存储文件的目录,并且出现错误

FileNotFoundError: [Errno 2] No such file or directory: 'media/upload/vertical_image.jpg'.
我实际上正在寻找一种方法来完成保存方法中的所有处理

这是我的媒体模型:

class Media(models.Model):
    title = models.CharField(max_length=255, null=True, blank=True)
    file = models.FileField(upload_to="upload/")
    filename = models.CharField(max_length=255, null=True, blank=True)
    mime_type = models.CharField(max_length=255, null=True, blank=True)
    thumbnail = models.JSONField(null=True, blank=True)
    size = models.FloatField(null=True, blank=True)
    url = models.CharField(max_length=300, null=True, blank=True)
    thumbhash = models.CharField(max_length=255, blank=True, null=True)
    is_public = models.BooleanField(blank=True, null=True)

    def save(self, *args, **kwargs):
        sizes = [(150, 150), (256, 256)]
        media_path = f"media/upload/{self.filename}"
        image = Image.open(media_path)

        mime_type = image.get_format_mimetype()
        format = mime_type.split("/")[1]

        if not os.path.exists("media/cache"):
            os.makedirs("media/cache")

        thumbnail = {}

        for i, size in enumerate(sizes):
            resized_image = image.resize(size)
            index = "small" if i == 0 else "medium"
            file_path = os.path.join(
                "media",
                "cache",
                f"{self.id}-resized-{self.filename}-{index}.{format}",
            )

            resized_image.save(file_path, format=format)
            thumbnail["*".join(str(i) for i in size)] = file_path

        self.mime_type = mime_type
        self.size = os.path.getsize(media_path)
        self.thumbnail = thumbnail
        self.url = f"http://127.0.0.1:8000/media/upload/{self.filename}"
        self.thumbhash = image_to_thumbhash(image)
        super().save(*args, **kwargs)

这是我的媒体序列化器:

class MediaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Media
        fields = [
            "id",
            "title",
            "file",
            "filename",
        ]

        def create(self, validated_data):
            return Media(**validated_data)```
python django django-models django-rest-framework django-signals
1个回答
0
投票

先获取图像字节,对字节进行处理,然后写入文件字节。

class Media(models.Model):
    file = models.FileField(upload_to="upload/")

    def save(self, *args, **kwargs):
        file_byte = self.file.read()
        file_byte_processed = your_process(file_byte)
        self.file.write(file_byte_processed)

        return super().save(*args, **kwargs)
© www.soinside.com 2019 - 2024. All rights reserved.