3
使用django-storages package當我刪除一個對象時,它不會從S3文件存儲中刪除圖像。我知道沒有其他物體使用相同的圖像。django-storages不會從S3中刪除
有人會知道這裏發生了什麼是有沒有我不知道的默認?
models.py
class Product(models.Model):
title = models.CharField(max_length=60,)
description = models.TextField(max_length=300,)
price = models.DecimalField(max_digits=8, decimal_places=2,)
qr_url = models.URLField(blank=True, verbose_name="QR Code URL", help_text="Read only generated automatically.")
qr_image = models.ImageField(
upload_to="qr-codes",
height_field="qr_image_height",
width_field="qr_image_width",
null=True,
blank=True,
editable=True,
verbose_name="QR Code Image"
)
qr_image_height = models.PositiveIntegerField(null=True, blank=True, editable=False)
qr_image_width = models.PositiveIntegerField(null=True, blank=True, editable=False)
#FK
category = models.ManyToManyField(ProductCategory)
def product_pre_save(sender, instance, **kwargs):
if not instance.pk:
instance._QRCODE = True
else:
if hasattr(instance, '_QRCODE'):
instance._QRCODE = False
else:
instance._QRCODE = True
models.signals.pre_save.connect(product_pre_save, sender=Product)
def product_post_save(sender, instance, **kwargs):
if hasattr(instance, '_already_saving'):
del instance._already_saving
return
if instance._QRCODE:
instance._QRCODE = False
if instance.qr_image:
instance.qr_image.delete()
# Create url
instance.qr_url = instance.create_QR_URL()
qr = QRCode(4, QRErrorCorrectLevel.L)
qr.addData(instance.qr_url)
qr.make()
image = qr.makeImage()
#Save image to string buffer
image_buffer = StringIO()
image.save(image_buffer, format='JPEG')
image_buffer.seek(0)
#Here we use django file storage system to save the image.
file_name = 'UrlQR_%s.jpg' % instance.id
file_object = File(image_buffer, file_name)
content_file = ContentFile(file_object.read())
instance._already_saving = True
instance.qr_image.save(file_name, content_file, save=True)
models.signals.post_save.connect(product_post_save, sender=Product)