1👍
✅
Just override the models delete
method:
import os
class File(models.Model):
title = models.CharField(max_length=400, help_text="Enter the title of the file, this will appear on the listings page")
CATEGORY_CHOICES = (
('Image', 'Image'),
('PDF', 'PDF')
)
file_type = models.CharField(choices=CATEGORY_CHOICES, help_text="Please select a file type", max_length=200)
file_upload = models.FileField(upload_to=get_upload_to)
def delete(self, *args, **kwargs):
path=self.file_upload.path
os.remove(path)
super(File,self).delete(*args, **kwargs)
This will work only deleting the entity, not with bulk_delete
. If you want to handle those within the admin view, you will have to create a default admin action like this:
from django.contrib import admin
from models import *
def delete_selected(modeladmin, request, queryset):
for element in queryset:
element.delete()
delete_selected.short_description = "Delete selected elements"
class FileAdmin(admin.ModelAdmin):
model = File
actions = [delete_selected]
list_display = ('title', 'file_type')
admin.site.register(File, FileAdmin)
Hope it helps!
Source:stackexchange.com