How to delete old image when update ImageField?

前端 未结 8 1616
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 09:20

I\'m using Django to create a stock photo site, I have an ImageField in my model, the problem is that when the user updates the image field, the original image file isn\'t d

8条回答
  •  心在旅途
    2020-12-13 09:31

    Here is an app that deletes orphan files by default: django-smartfields. It will remove files whenever:

    • field value was replaced with a new one (either uploaded or set manually)
    • field is cleared through the form (in case that field is not required, of course)
    • the model instance itself containing the field is deleted.

    It is possible to turn that cleanup feature off using an argument: ImageField(keep_orphans=True) on per field basis, or globally in settings SMARTFIELDS_KEEP_ORPHANS = True.

    from django.db import models
    
    from smartfields import fields
    
    class MyModel(models.Model):
        image = fields.ImageField()
        document = fields.FileField()
    

提交回复
热议问题