Django 选择在模型的保存方法中加载图像的位置



以下是我的字段为image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True):的模型的保存方法

def save(self, *args, **kwargs):
if self.image:
self.image = compress(self.image)
if self.second_image:
self.second_image = compress(self.second_image)
if self.third_image:
self.third_image = compress(self.third_image)
if self.fourth_image:
self.fourth_image = compress(self.fourth_image)
super().save(*args, **kwargs)

它运行良好,可以压缩所有图像,但每次我在django-admin中单击保存时都会更改图像的目录。它使所有图像的路径如下:
编辑和保存之前:products/2020/11/05/img.jpeg
之后:products/2020/11/05/products/2020/11/05/img.jpeg
再次单击保存:products/2020/11/05/products/2020/11/05/products/2020/11/05/img.jpeg
然后我得到此错误:

SuspiciousFileOperation at /admin/shop/product/6/change/
Storage can not find an available filename for "products2020115products2020115products2020...... .jpeg".
Please make sure that the corresponding file field allows sufficient "max_length".

如何解决此问题?我想我需要选择保存图像的存储位置。Django不允许我在upload_to字段中使用绝对路径,所以我不知道。

压缩函数为:

from io import BytesIO
from PIL import Image
from django.core.files import File
def compress(image):
im = Image.open(image)
if im.mode != 'RGB':
im = im.convert('RGB')
im_io = BytesIO()
im.save(im_io, 'JPEG', quality=70)
compressed_image = File(im_io, name=image.name)
return compressed_image

问题是每次都会更新文件名。在每一步中,您都应该确保文件名只是一个文件名。类似这样的东西:

import os
if self.image:
self.image = compress(self.image)
self.image.name = os.path.basename(self.image.name)

我不知道你的压缩函数到底是什么,但也许你也可以检查一下它是否对文件名做了一些奇怪的事情。

最新更新