Question

models.py

    class Issue(models.Model):
        issueId = models.AutoField(primary_key=True)
        title = models.CharField(max_length = 20)
        year = models.IntegerField()
        issueDate = models.DateField()

    class Preview(models.Model):
        issueId = models.ForeignKey(Issue);
        previewPath = models.FileField(upload_to='./upload/magazine_sample')

admin.py

    class PreviewInline(object):
        model = Preview
        extra = 1
        style = 'accordion'
        max_num = 1

    class IssueAdmin(object):
        list_display = ('title',)
        inlines = [PreviewInline]

    admin.site.register(Issue, IssueAdmin)

How can I delete the preview and the uploaded file when I delete the Issue model? Can anyone help me please?

Was it helpful?

Solution

Are you sure the Issue is not being deleted? The defaul behavior for the ForeignKey is to cascade the deletion:

ForeignKey.on_delete When an object referenced by a ForeignKey is deleted, Django by default emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey. This behavior can be overridden by specifying the on_delete argument.

Are you using sqlite3? I'm not sure it has cascading enabled by default.

To delete the image, you might want to use the pre_delete signal:

from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import Preview

@receiver(pre_delete, sender=Preview)
def delete_image(sender, instance, using):
    # delete the image -> instance.previewPath

More info on signals: https://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.pre_delete https://docs.djangoproject.com/en/dev/topics/signals/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top