4

当我删除一个对象时使用django-storages 包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)
4

1 回答 1

4

在您的 post_save 操作中,您有:

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

这不起作用,因为您试图删除一个字段,而不是实例,这就是 Boto 不会删除文件的原因。

有关如何使用 Boto 删除单个文件的示例,请参阅此答案。

于 2013-02-22T16:29:34.893 回答