I have the following Folder model which represents all the folders I have inside a directory :
class Folder(models.Model):
folder_name = models.CharField(max_length=200)
parent_folder = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='childrens')
def __init__(self, *args, **kwargs):
super(Folder, self).__init__(*args, **kwargs)
if self.pk is not None:
self.initial_filepath = self.filepath()
def save(self, *args, **kwargs):
on_creation = self.pk is None
if on_creation:
os.mkdir(self.filepath())
else:
os.rename(self.initial_filepath, self.filepath())
super(Folder, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
shutil.rmtree(self.filepath(), ignore_errors=True)
super(Folder, self).delete(*args, **kwargs)
def filepath(self):
if not self.parent_folder:
return f'media/scripts/{self.folder_name}'
else:
return f'{self.parent_folder.filepath()}/{self.folder_name}'
The problem is, when I'm in the admin page and I try to delete a folder, if it has subfolders in it (i.e. if the folder I'm deleting is the parent_folder of another folder instance) it doesn't delete any of the selected folders and returns a RecursionError after a few seconds.
I've checked my code, and I don't see any recursion loop inside my own code, and I didn't manage to determine where it was coming from.
I've also overriden the delete_queryset method in my admin.py but the issue doesn't seem to come from there as it still doesn't work if I try to delete my parent folder from inside the page to modify my folder.
class FolderAdmin(admin.ModelAdmin):
def delete_queryset(self, request, queryset):
for obj in queryset:
obj.delete()
queryset.delete()
The folders are deleted on my computer so the delete method is called, no problem. My guess is that it's coming from my ForeignKey but I have absolutely no idea how to solve this issue.
EDIT : I just found out that there was a recursion in the error that can help to solve my problem :
Traceback (most recent call last):
File "C:\Users\stephane.bernardelli\Documents\AppliScripts\lib\site-packages\django\db\models\fields\related_descriptors.py", line 173, in __get__
rel_obj = self.field.get_cached_value(instance)
File "C:\Users\stephane.bernardelli\Documents\AppliScripts\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value
return instance._state.fields_cache[cache_name]
During handling of the above exception ('parent_folder'), another exception occurred:
File "C:\Users\stephane.bernardelli\Documents\AppliScripts\lib\site-packages\django\db\models\fields\related_descriptors.py", line 173, in __get__
rel_obj = self.field.get_cached_value(instance)
File "C:\Users\stephane.bernardelli\Documents\AppliScripts\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value
return instance._state.fields_cache[cache_name]
The During the handling of the above exception... part is repeated like 30 times before the traceback changes to something else.