gpt4 book ai didi

django-storages 不会从 S3 中删除

转载 作者:行者123 更新时间:2023-12-01 01:11:49 25 4
gpt4 key购买 nike

使用 django-storages package S3 当我删除一个对象时,它不会从我的 S3 文件存储中删除图像。我知道没有其他对象使用相同的图像。

有谁知道这里发生了什么,有一个我不知道的默认值吗?

模型.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)

最佳答案

在您的 post_save 操作中,您有:

...
if instance.qr_image:
instance.qr_image.delete()
...

这是行不通的,因为您要删除的是字段,而不是实例,这就是 Boto 不会删除文件的原因。

See this answer有关如何使用 Boto 删除单个文件的示例。

关于django-storages 不会从 S3 中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15028237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com