diff --git a/base/views.py b/base/views.py index 7c358331..5b95ff27 100644 --- a/base/views.py +++ b/base/views.py @@ -4,11 +4,14 @@ # standard library # django +from django.db.models import ProtectedError from django.conf import settings +from django.contrib import messages from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import AccessMixin from django.core.exceptions import ImproperlyConfigured +from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.shortcuts import render from django.urls import reverse @@ -308,6 +311,24 @@ def get_success_url(self): model_name = self.model.__name__.lower() return reverse('{}_list'.format(model_name)) + def post(self, request, *args, **kwargs): + try: + return self.delete(request, *args, **kwargs) + except ProtectedError as error: + return self.handle_protected_error(request, error) + + def handle_protected_error(self, request, error): + """ + Overwrite this method if you want to change the error message or + redirect to a different view. + """ + messages.add_message( + request, + messages.ERROR, + _("This object cannot be deleted."), + ) + return HttpResponseRedirect(self.object.get_absolute_url()) + class BaseRedirectView(LoginPermissionRequiredMixin, RedirectView): login_required = True