已从数据库中删除的图像也将从存储中删除

时间:2011-10-26 18:48:25

标签: python django

我有这些模特:

class Gallery(models.Model):
   HeadImage = models.ImageField(upload_to="gallery")

class Image(models.Model):
   Image = models.ImageField(upload_to="gallery")
   Gallery = models.ForeignKey(Gallery, related_name='images')

class Tour(models.Model):
   Name=models.CharField(max_length=100)
   Count=models.SmallIntegerField() 
   PriceUnit=models.ForeignKey(PriceUnit)
   Price=models.CharField(max_length=12)
   Gallery = models.OneToOneField(Gallery,editable=False)

因为你可以看到每个巡演有一个图像库,我设计了一个允许用户添加巡视的ModelForm,这是它在views.py中的代码:

def addtour(request,key):
   ImageFormSet = inlineformset_factory(Gallery,Image, can_delete=False,extra=4)
   if request.method == 'POST':
      gform=GalleryForm(request.POST,request.FILES)
      if gform.is_valid():
         gallery=gform.save(commit=False)
         formset=ImageFormSet(request.POST, request.FILES, instance=gallery)
      if formset.is_valid():
         gallery.save()
         formset.save()
      tform = TourForm(request.POST, request.FILES)
      if tform.is_valid():
         tour=tform.save(commit=False)
         tour.ActionUserCode=User.objects.get(pk=1)
         tour.Gallery=gallery
         tour.save()
         return HttpResponseRedirect(reverse('airAgency.views.edittour', args=[agn.WebSite,tour.pk]))#'airAgency/edittour/%i/' % (tour.pk))
   else:
      tform = TourForm()
      gform=GalleryForm()
      galleryinstance=Gallery()
      formset=ImageFormSet(instance=galleryinstance)
   return render_to_response('airAgency/addtour.html', {'tform': tform,'gform':gform,'formset':formset})

正如你可以在视图中看到的,添加游览后,用户被重定向到编辑页面。现在我想当编辑页面中的用户删除游览或当图像属于它时删除图库,另外还要从存储中删除图像从数据库中删除。我可以处理这个吗?

1 个答案:

答案 0 :(得分:1)

您可以覆盖模型上的delete()方法以执行您想要的操作。

https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods

class Image:
    #other code is here

    def delete(self, *args, **kwargs):
        #code to remove from file system goes here
        super(Image, self).delete(*args, **kwargs)