Issue
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})
Solution
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)
Answered By - Shakil Ahmmed
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.