I have these models:
我有这些模型:
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)
as U can see each tour has a gallery of images,I've designed a ModelForm that let user add a tour,this is it's code in views.py:
因为你可以看到每个巡演有一个图像库,我设计了一个允许用户添加巡视的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})
as U can see in views,after adding a tour,user is redirected to edittour page.now I wanna when user in edittour page delete a tour or when Images belong to it's Gallery is deleted ,Images be deleteed from storage in addition to deleting from database.how can I handle this?
正如你可以在视图中看到的,在添加游览之后,用户被重定向到编辑页面。现在我想当编辑页面中的用户删除游览或当图像属于它时删除图库,除了删除图像之外,还要从存储中删除图像。 database.how我可以处理这个吗?
1 个解决方案
#1
1
You can override the delete() method on a model to do what you want.
您可以覆盖模型上的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)
#1
1
You can override the delete() method on a model to do what you want.
您可以覆盖模型上的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)