我在django中创建了一个基本文件应用程序,因此客户可以上传文件并复制相关网址并在网站内容中使用它。该应用程序的一个想法是,一旦删除了一个条目,该文件将从服务器中删除,以帮助清理空间并保持服务器整洁。
然而,当我添加一个条目(文件)时,它会上传到正确的目录。但是,当我删除它时,文件仍保留在服务器上。有没有办法删除文件以及条目(文件)。
以下是代码:
from django.db import models
def get_upload_to(instance, filename):
if instance.file_type == 'Image':
return "images/filesApp/%s" % filename
elif instance.file_type == 'PDF':
return "pdf/filesApp/%s" % filename
return "filesApp/%s" % filename
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)
谢谢!
答案 0 :(得分:1)
只需覆盖模型delete
方法:
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)
这只会删除实体,而不是bulk_delete
。如果要在管理视图中处理这些操作,则必须创建如下默认管理操作:
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)
希望它有所帮助!