2

please help! I am using Django 3 and have a basic blog with a title, description and image for each entry. In Django admin I can delete each blog post however, when I look in my media file in Atom all the images are still there and I have to manually delete them...

how do I get them to auto delete when I delete them in Admin?

Model.py

from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    image = models.ImageField(upload_to='images/', default='images/road.jpg')
    last_modified = models.DateField(auto_now=True)

Views.py

from django.shortcuts import render
from .models import Blog

def home (request):
    blogs = Blog.objects.all()
    return render (request,'blog/home.html', {'blogs':blogs})
the_end
  • 67
  • 9
  • Does this answer your question? [How do I get Django Admin to delete files when I remove an object from the database/model?](https://stackoverflow.com/questions/5372934/how-do-i-get-django-admin-to-delete-files-when-i-remove-an-object-from-the-datab) – shad0w_wa1k3r Jun 05 '20 at 09:37
  • Also, this might be helpful - [Django delete FileField](https://stackoverflow.com/questions/16041232/django-delete-filefield) – shad0w_wa1k3r Jun 05 '20 at 09:37
  • use it forgienkey(on_delete = models.CASCAD) !! in you'r model.py – SALAH EDDINE ELGHARBI Jun 05 '20 at 10:04

2 Answers2

1

You can use like this:

    blog = Blog.objects.get(pk=1)
    if blog.image:
        if os.path.isfile(blog.image.path):
           os.remove(blog.image.path)

Or You Can Use signlas:

from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver

@receiver(pre_delete, sender=Blog)
def mymodel_delete(sender, instance, **kwargs):
    # Pass false so FileField doesn't save the model.
    instance.file.delete(False)
1

Use django-cleanup app for automatically remove the media when you delete your objects.

star700p
  • 21
  • 3
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Tyler2P Feb 27 '21 at 18:50