在我的Django应用中,用户可以上传并存储文件或查看或删除它们。我知道在Django的较新版本中,如果删除了Model实例,它将无法处理实际文件的删除。但是我也很快发现在.delete()
上调用FileField()
方法可以完成这项工作。因此,我修改了Model类的delete()
方法。但是我收到一些PermissionErorr,显然它拒绝删除文件。这是我的代码
class Attachments(models.Model):
content = models.FileField(null=True, blank=True, upload_to=get_attachment_dir, help_text="Add important documents or pictures")
parent_task = models.ForeignKey(ToDo, on_delete=models.CASCADE)
uploaded_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Attachments of {self.parent_task.title}"
def delete(self, *args, **kwargs):
self.content.delete()
super(Attachments, self).delete(*args,**kwargs)
错误指出
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\User\\Desktop\\Python Development\\Django_ToDo_App\\media\\users\\arafat_ar13_1\\task_attachments\\257\\Calculator.py'
我应该如何解决此错误并真正删除文件,以免在用户使用完该文件后不会占用我的服务器空间?感谢您的任何事先帮助。