Answer the question
In order to leave comments, you need to log in
How to delete all files associated with a model?
Tell me how to remove the ad and all the photos attached to it?
Here are the models
class Advert(models.Model):
user = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length=30)
ad_type = models.CharField(max_length=30)
category = models.TextField()
title = models.CharField(max_length=64)
sex = models.CharField(max_length=7)
description = models.CharField(max_length=2000)
class AdvertPhoto(models.Model):
advert = models.ForeignKey('Advert')
photo = models.ImageField(upload_to='')
preview = models.BooleanField(default=False)
def __str__(self):
return str(self.advert)
Answer the question
In order to leave comments, you need to log in
Tons of options. For example:
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
@receiver(pre_delete, sender=AdvertPhoto)
def advert_photo_delete(sender, instance, **kwargs):
instance.file.delete(False)
import os
for instance in AdvertPhoto.objects.all():
os.remove(instance.photo.path)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question