diff --git a/hypha/apply/middleware.py b/hypha/apply/middleware.py index b8ee4623069fe349f938506df2abe04a4df92673..d102af28517fdba888a728dc7ddedb3058324c61 100644 --- a/hypha/apply/middleware.py +++ b/hypha/apply/middleware.py @@ -1,8 +1,30 @@ +from django.contrib import messages +from django.db.models.deletion import ProtectedError +from django.http import HttpResponseRedirect from wagtail.core.models import Site from .home.models import ApplyHomePage +class HandleProtectionErrorMiddleware: + def __init__(self, get_response): + self.get_response = get_response + + def process_exception(self, request, exception): + if isinstance(exception, ProtectedError): + messages.error( + request, + "The object you are trying to delete is used somewhere. Please remove any usages and try again!.", + ) + return HttpResponseRedirect(request.path) + + return None + + def __call__(self, request): + response = self.get_response(request) + return response + + def apply_url_conf_middleware(get_response): # If we are on a page which belongs to the same site as an ApplyHomePage # we change the url conf to one that includes links to all the logged diff --git a/hypha/settings/base.py b/hypha/settings/base.py index 574cbf99a3f4dde1de4875016a91c602cf5eb01f..3d7ff7f11d24e55dcbc31f77325a7f2bd8fbda92 100644 --- a/hypha/settings/base.py +++ b/hypha/settings/base.py @@ -171,6 +171,7 @@ MIDDLEWARE = [ 'wagtail.contrib.redirects.middleware.RedirectMiddleware', 'hypha.apply.middleware.apply_url_conf_middleware', + 'hypha.apply.middleware.HandleProtectionErrorMiddleware', ] ROOT_URLCONF = 'hypha.urls'