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})
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.
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.
def sampleView(request):
model = YourModel.objects.get(id=id)
model.delete()
Use django-cleanup app for automatically remove the media when you delete your objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With