#model.py
from django.db import models
# Create your models here.
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from user.models import User
class ImgFiles(models.Model):
user=models.CharField('用户名',max_length=64,null=True,blank=True)
name=models.CharField('图片名',max_length=300)
img=models.ImageField('图片地址',upload_to='images')
create_time=models.DateField('上传日期',auto_now_add=True)
class Meta:
verbose_name='图片列表'
verbose_name_plural=verbose_name
@receiver(pre_delete, sender=ImgFiles) #sender=你要删除或修改文件字段所在的类**
def file_delete(instance, **kwargs): #函数名随意
print('进入文件删除方法,删的是',instance.img) #用于测试
instance.img.delete(False) #file是保存文件或图片的字段名**
views.py:
@csrf_exempt
def delete_file(request):
file=request.POST.get('file')
img=ImgFiles.objects.filter(img=file.split(settings.MEDIA_URL)[1])
print(img)
if not img:
return HttpResponse('图片地址错误')
for i in img:
file_delete(instance=i)
i.delete()
return HttpResponse('ok')