Skip to content

Commit

Permalink
[admin] Fixed FileNotFoundError openwisp#140
Browse files Browse the repository at this point in the history
The change_view associated with BuildAdmin class was throwing
an exception when trying to delete a FirmwareImage object,
when the file associated with that object had already been
deleted from the file system.

There were two tasks according to my understanding:
1. Prevent the website to break and catch the error:
        the return expression in change_view has been put
in a try/catch expression, with instructions/hints/warnings
for the user using message_user

2. If an image file has been deleted from the filesystem,
automatically remove the FirmwareImage assiciated with it:

        The 'get_queryset' method for FirmwareImageInline class
has been over-written to automatically remove FirmwareImage objects
associated with deleted files and the information has been
logged with logger.

Fixes openwisp#140
  • Loading branch information
AbhigyaShridhar committed Feb 22, 2022
1 parent 91fe0b2 commit 0e78ce8
Showing 1 changed file with 48 additions and 2 deletions.
50 changes: 48 additions & 2 deletions openwisp_firmware_upgrader/admin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
import os
from datetime import timedelta

import reversion
Expand All @@ -7,7 +8,7 @@
from django.conf import settings
from django.contrib import admin, messages
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.shortcuts import redirect
from django.shortcuts import HttpResponseRedirect, redirect
from django.template.response import TemplateResponse
from django.urls import resolve, reverse
from django.utils.safestring import mark_safe
Expand Down Expand Up @@ -84,6 +85,37 @@ def has_change_permission(self, request, obj=None):
return False
return True

def get_parent_object(self, request):
"""
method to get the instance from model' s parent class
in context with the ForeignKey relation
"""
resolved = resolve(request.path_info)
if resolved.kwargs:
return self.parent_model.objects.get(pk=resolved.kwargs["object_id"])
return None

def get_queryset(self, request):
"""
overriding queryset to remove any FirmwareImage instances,
where the image file has been manually deleted by the user
from the file system
"""
qs = super(FirmwareImageInline, self).get_queryset(request)
build = self.get_parent_object(request)
qs = qs.filter(build=build)
for imageObject in qs:
if imageObject.file is not None:
path = imageObject.file.path
if not os.path.isfile(path):
try:
type = imageObject.type
imageObject.delete()
logger.warning(f"Image object {type} was removed")
except Exception:
pass
return qs


class CategoryFilter(MultitenantOrgFilter):
multitenant_lookup = 'organization_id__in'
Expand Down Expand Up @@ -192,7 +224,21 @@ def change_view(self, request, object_id, form_url='', extra_context=None):
extra_context = extra_context or {}
upgrade_url = f'{app_label}_build_changelist'
extra_context.update({'upgrade_url': upgrade_url})
return super().change_view(request, object_id, form_url, extra_context)
# preventing change_view to throw an error/exception
try:
return super().change_view(request, object_id, form_url, extra_context)
except Exception as e:
if type(e).__name__ == "FileNotFoundError":
self.message_user(
request, "Please reload the page", level=logging.ERROR
)
else:
self.message_user(
request,
"Image objects have been removed or form data didn't validate",
level=logging.ERROR,
)
return HttpResponseRedirect(request.path)


class UpgradeOperationForm(forms.ModelForm):
Expand Down

0 comments on commit 0e78ce8

Please sign in to comment.