Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I automatically delete images in Django media file when I delete the objects in Admin?

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})
like image 651
the_end Avatar asked Jan 31 '26 22:01

the_end


2 Answers

You can delete media files in different ways, but the most easy and convenient way is to delete them with the help of models. Just override the delete() method and delete that object in that custom delete() method.

  • models.py
class YourModel(models.Model):
    # Other fields in your model
    field1 = models.CharField(max_length=255)
    field2 = models.IntegerField()
    
    # Media file field
    media_file = models.FileField(upload_to='media/')

    def delete(self, *args, **kwargs):
        self.media_file.delete()
        super(YourModel, self).delete(*args, **kwargs)

What does the above code do? When you execute the delete() method, it will automatically delete the media file as well.

  • views.py
def sampleView(request):
    model = YourModel.objects.get(id=id)
    model.delete()
like image 197
Mayank Gupta Avatar answered Feb 02 '26 12:02

Mayank Gupta


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

like image 39
star700p Avatar answered Feb 02 '26 12:02

star700p