1.存在问题
django中的文件和图片字段分别为FileField和ImageField,更新和删除时,未能同步更改存储文件。
2.解决问题
参考链接:https://www.it1352.com/641991.html
https://www.cnblogs.com/ddb1-1/p/12434881.html
model.py
#模板文件
class Template(models.Model):
file = models.FileField(upload_to='Workafter/notice/%Y/%m', verbose_name=u'模板文件', null=True, blank=True)
注意:需要自行修改的代码为
sender=Template和file
#修改和删除数据时,删除旧图片,保存新图
from django.db.models.signals import pre_delete,post_save,post_init
from django.dispatch.dispatcher import receiver
#删除时
@receiver(pre_delete, sender=Template)
def delete(sender, instance, **kwargs):
# Pass false so FileField doesn't save the model.
instance.file.delete(False)
#修改时
@receiver(post_init, sender=Template)
def file_path(sender, instance, **kwargs):
instance._current_file = instance.file
@receiver(post_save, sender= Template)
def delete_old_image(sender, instance, **kwargs):
if hasattr(instance, '_current_file'):
if instance._current_file != instance.file.path:
instance._current_file.delete(save=False)