Python django.db.models.ProtectedError() Examples

The following are 30 code examples of django.db.models.ProtectedError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.models , or try the search function .
Example #1
Source File: product.py    From Servo with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def delete_product(request, pk, group):
    from django.db.models import ProtectedError
    product = get_object_or_404(Product, pk=pk)

    if request.method == 'POST':
        try:
            product.delete()
            Inventory.objects.filter(product=product).delete()
            messages.success(request, _("Product deleted"))
        except ProtectedError:
            messages.error(request, _('Cannot delete product'))

        return redirect(list_products, group)

    action = request.path
    return render(request, 'products/remove.html', locals()) 
Example #2
Source File: device.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def delete_device(request, product_line, model, pk):
    dev = get_object_or_404(Device, pk=pk)

    if request.method == 'POST':
        from django.db.models import ProtectedError
        try:
            dev.delete()
            messages.success(request, _("Device deleted"))
        except ProtectedError:
            messages.error(request, _("Cannot delete device with GSX repairs"))
            return redirect(dev)

        return redirect(index)

    data = {'action': request.path}
    data['device'] = dev

    return render(request, "devices/remove.html", data) 
Example #3
Source File: test__transition_approval.py    From django-river with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_shouldNotAllowWorkflowToBeDeletedWhenThereIsATransitionApproval(self):
        content_type = ContentType.objects.get_for_model(BasicTestModel)

        state1 = StateObjectFactory(label="state1")
        state2 = StateObjectFactory(label="state2")

        workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")

        transition_meta = TransitionMetaFactory.create(
            workflow=workflow,
            source_state=state1,
            destination_state=state2,
        )

        TransitionApprovalMetaFactory.create(workflow=workflow, transition_meta=transition_meta, priority=0)

        BasicTestModelObjectFactory()
        TransitionApproval.objects.filter(workflow=workflow).update(status=APPROVED)
        approvals = TransitionApproval.objects.filter(workflow=workflow)
        assert_that(approvals, has_length(1))

        assert_that(
            calling(workflow.delete),
            raises(ProtectedError, "Cannot delete some instances of model 'Workflow' because they are referenced through a protected foreign key")
        ) 
Example #4
Source File: templates.py    From loom with GNU Affero General Public License v3.0 6 votes vote down vote up
def delete(self):
        from api.models.data_nodes import DataNode
        if self.parents.count() != 0:
            raise models.ProtectedError(
                'Cannot delete template "@%s" because it is contained by '
                '1 or more other templates' % self.uuid, 
                [template for template in self.parents.all()])
        nodes_to_delete = set()
	queryset = DataNode.objects.filter(
            templateinput__template__uuid=self.uuid)
        for item in queryset.all():
            nodes_to_delete.add(item)
        super(Template, self).delete()
        for item in nodes_to_delete:
            try:
                item.delete()
            except models.ProtectedError:
                pass 
Example #5
Source File: views.py    From hypha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def custom_wagtail_page_delete(request, page_id):
    """
    Currently, ProtectedError exception is not caught in Wagtail admin.
    This workaround shows warning to the user if the page model like Fund, Round
    can not be deleted instead of raising 500.
    More details at https://github.com/wagtail/wagtail/issues/1602
    Once the issue is fixed in Wagtail core, we can remove this workaround.
    """
    try:
        return delete(request, page_id)
    except ProtectedError as e:
        protected_details = ", ".join([str(obj) for obj in e.protected_objects])
        page = get_object_or_404(Page, id=page_id).specific
        parent_id = page.get_parent().id
        messages.warning(request, _("Page '{0}' can't be deleted because is in use in '{1}'.").format(
            page.get_admin_display_title(), protected_details
        ))
        return redirect('wagtailadmin_explore', parent_id) 
Example #6
Source File: models.py    From zing with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, *args, **kwargs):
        """Deletes a user instance.

        Trying to delete a meta user raises the `ProtectedError` exception.
        """
        if self.is_meta:
            raise ProtectedError("Cannot remove meta user instances", None)

        purge = kwargs.pop("purge", False)

        if purge:
            UserPurger(self).purge()
        else:
            UserMerger(self, User.objects.get_nobody_user()).merge()

        super().delete(*args, **kwargs) 
Example #7
Source File: views.py    From loom with GNU Affero General Public License v3.0 5 votes vote down vote up
def destroy(self, *args, **kwargs):
        if get_setting('DISABLE_DELETE'):
            return JsonResponse({
                'message': 'Delete is forbidden because DISABLE_DELETE is True.'},
                                status=403)
        else:
            try:
                return super(ProtectedDeleteModelViewSet, self).destroy(
                    *args, **kwargs)
            except ProtectedError:
                return JsonResponse({
                        'message':
                        'Delete failed because resource is still in use.'},
                                    status=409) 
Example #8
Source File: test_models.py    From openwisp-radius with GNU General Public License v3.0 5 votes vote down vote up
def test_delete_default_group(self):
        group = RadiusGroup.objects.get(default=1)
        try:
            group.delete()
        except ProtectedError:
            pass
        else:
            self.fail('ProtectedError not raised') 
Example #9
Source File: runs.py    From loom with GNU Affero General Public License v3.0 5 votes vote down vote up
def delete(self):
        from api.models.data_nodes import DataNode
        nodes_to_delete = set()
        for queryset in [
                DataNode.objects.filter(runinput__run__uuid=self.uuid),
                DataNode.objects.filter(runoutput__run__uuid=self.uuid),
                DataNode.objects.filter(userinput__run__uuid=self.uuid),
                DataNode.objects.filter(taskinput__task__run__uuid=self.uuid),
                DataNode.objects.filter(taskoutput__task__run__uuid=self.uuid),
                DataNode.objects.filter(
                    taskattemptinput__task_attempt__tasks__run__uuid=self.uuid),
                DataNode.objects.filter(
                    taskattemptoutput__task_attempt__tasks__run__uuid=self.uuid)
        ]:
            for item in queryset.all():
                nodes_to_delete.add(item)

        # TaskAttempt will not be deleted if shared with another run
        task_attempts_to_cleanup = [item for item in TaskAttempt.objects.filter(
            tasks__run__uuid=self.uuid)]

        super(Run, self).delete()
        for item in nodes_to_delete:
            try:
                item.delete()
            except models.ProtectedError:
                pass
        for task_attempt in task_attempts_to_cleanup:
            task_attempt.cleanup() 
Example #10
Source File: transaction.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        success_url = self.get_success_url()

        try:
            self.object.delete()
        except ProtectedError:
            messages.add_message(request, messages.ERROR, 'Can not delete this Transaction!')
            return HttpResponseRedirect(self.object.get_absolute_url())

        return HttpResponseRedirect(success_url) 
Example #11
Source File: model.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        success_url = self.get_success_url()

        try:
            self.object.delete()
        except ProtectedError:
            messages.add_message(request, messages.ERROR, 'Can not delete: this Model is being used!')
            return HttpResponseRedirect(self.object.get_absolute_url())

        return HttpResponseRedirect(success_url) 
Example #12
Source File: tag.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        success_url = self.get_success_url()

        try:
            self.object.delete()
        except ProtectedError:
            messages.add_message(request, messages.ERROR, 'Can not delete: this Tag is being used!')
            return HttpResponseRedirect(self.object.get_absolute_url())

        return HttpResponseRedirect(success_url) 
Example #13
Source File: models.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def check_tag_can_delete(sender, instance, using, **kwargs):
    if not instance.can_delete():
        raise ProtectedError('This Tag is being used', instance) 
Example #14
Source File: models.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def check_model_can_delete(sender, instance, using, **kwargs):
    if not instance.can_delete():
        raise ProtectedError('This Model is being used', instance) 
Example #15
Source File: util.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def collect(self, objs, source_attr=None, **kwargs):
        for obj in objs:
            if source_attr and hasattr(obj, source_attr):
                self.add_edge(getattr(obj, source_attr), obj)
            else:
                self.add_edge(None, obj)
        try:
            return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
        except models.ProtectedError as e:
            self.protected.update(e.protected_objects) 
Example #16
Source File: views.py    From wagtailmodeladmin with MIT License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        if request.POST:
            try:
                self.delete_instance()
                messages.success(
                    request,
                    _("{model} '{instance}' deleted.").format(
                        model=self.model_name, instance=self.instance))
                return redirect(self.get_index_url)
            except models.ProtectedError:
                messages.error(
                    request, _(
                        "{model} '{instance}' could not be deleted."
                    ).format(model=self.model_name, instance=self.instance))

                linked_objects = []
                for rel in self.model._meta.get_all_related_objects():
                    if rel.on_delete == models.PROTECT:
                        qs = getattr(self.instance, rel.get_accessor_name())
                        for obj in qs.all():
                            linked_objects.append(obj)

                context = {
                    'view': self,
                    'instance': self.instance,
                    'error_protected': True,
                    'linked_objects': linked_objects,
                }
        return self.render_to_response(context) 
Example #17
Source File: utils.py    From python2017 with MIT License 5 votes vote down vote up
def collect(self, objs, source=None, source_attr=None, **kwargs):
        for obj in objs:
            if source_attr and not source_attr.endswith('+'):
                related_name = source_attr % {
                    'class': source._meta.model_name,
                    'app_label': source._meta.app_label,
                }
                self.add_edge(getattr(obj, related_name), obj)
            else:
                self.add_edge(None, obj)
            self.model_objs[obj._meta.model].add(obj)
        try:
            return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
        except models.ProtectedError as e:
            self.protected.update(e.protected_objects) 
Example #18
Source File: util.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def collect(self, objs, source_attr=None, **kwargs):
        for obj in objs:
            if source_attr and hasattr(obj, source_attr):
                self.add_edge(getattr(obj, source_attr), obj)
            else:
                self.add_edge(None, obj)
        try:
            return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
        except models.ProtectedError as e:
            self.protected.update(e.protected_objects) 
Example #19
Source File: util.py    From devops with MIT License 5 votes vote down vote up
def collect(self, objs, source=None, source_attr=None, **kwargs):
        for obj in objs:
            if source_attr and not source_attr.endswith('+'):
                related_name = source_attr % {
                    'class': source._meta.model_name,
                    'app_label': source._meta.app_label,
                }
                self.add_edge(getattr(obj, related_name), obj)
            else:
                self.add_edge(None, obj)
            self.model_count[obj._meta.verbose_name_plural] += 1
        try:
            return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
        except models.ProtectedError as e:
            self.protected.update(e.protected_objects) 
Example #20
Source File: testing.py    From open-humans with MIT License 5 votes vote down vote up
def test_protected_deletion(self):
        with self.assertRaises(ProtectedError):
            self.member1_project.delete() 
Example #21
Source File: util.py    From online with GNU Affero General Public License v3.0 5 votes vote down vote up
def collect(self, objs, source_attr=None, **kwargs):
        for obj in objs:
            if source_attr and hasattr(obj, source_attr):
                self.add_edge(getattr(obj, source_attr), obj)
            else:
                self.add_edge(None, obj)
        try:
            return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
        except models.ProtectedError as e:
            self.protected.update(e.protected_objects) 
Example #22
Source File: util.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def collect(self, objs, source_attr=None, **kwargs):
        for obj in objs:
            if source_attr and hasattr(obj, source_attr):
                self.add_edge(getattr(obj, source_attr), obj)
            else:
                self.add_edge(None, obj)
        try:
            return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
        except models.ProtectedError as e:
            self.protected.update(e.protected_objects) 
Example #23
Source File: util.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def collect(self, objs, source_attr=None, **kwargs):
        for obj in objs:
            if source_attr and hasattr(obj, source_attr):
                self.add_edge(getattr(obj, source_attr), obj)
            else:
                self.add_edge(None, obj)
        try:
            return super(NestedObjects, self).collect(objs, source_attr=source_attr, **kwargs)
        except models.ProtectedError, e:
            self.protected.update(e.protected_objects) 
Example #24
Source File: test_vlan.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_raises_integrity_error_if_reconnecting_fails(self):
        # Here we test a corner case: we test that the DB refuses to
        # leave an interface without a VLAN in case the reconnection
        # fails when a VLAN is deleted.
        vlan = factory.make_VLAN()
        # Break 'manage_connected_interfaces'.
        self.patch(vlan, "manage_connected_interfaces")
        factory.make_Interface(INTERFACE_TYPE.PHYSICAL, vlan=vlan)
        with ExpectedException(ProtectedError):
            vlan.delete() 
Example #25
Source File: test_domain.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_cant_be_deleted_if_contains_resources(self):
        domain = factory.make_Domain()
        factory.make_DNSResource(domain=domain)
        with ExpectedException(ProtectedError):
            domain.delete() 
Example #26
Source File: models.py    From openwisp-radius with GNU General Public License v3.0 5 votes vote down vote up
def delete(self, *args, **kwargs):
        if self.default:
            raise ProtectedError(self._DEFAULT_PROTECTED_ERROR, self)
        return super().delete(*args, **kwargs) 
Example #27
Source File: test_openedx_monitoring_mixins.py    From opencraft with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_deleting_shared_notification_email_address(self, mock_consul):
        """
        Test that a shared email notification channel can't be deleted.
        Shared notification channels are used by many instances, so if one instance deleted it, the others
        wouldn't be able to use it.
        """
        e = NewRelicEmailNotificationChannel.objects.create(id=1, email='test@opencraft.com', shared=True)
        with self.assertRaises(ProtectedError):
            e.delete() 
Example #28
Source File: test__transition_approval.py    From django-river with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_shouldNotAllowTheStateToBeDeletedWhenThereIsATransitionApprovalThatIsUsedAsSource(self):
        content_type = ContentType.objects.get_for_model(BasicTestModel)

        state1 = StateObjectFactory(label="state1")
        state2 = StateObjectFactory(label="state2")
        state3 = StateObjectFactory(label="state3")

        workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")

        transition_meta_1 = TransitionMetaFactory.create(
            workflow=workflow,
            source_state=state1,
            destination_state=state2,
        )

        transition_meta_2 = TransitionMetaFactory.create(
            workflow=workflow,
            source_state=state2,
            destination_state=state3,
        )

        TransitionApprovalMetaFactory.create(workflow=workflow, transition_meta=transition_meta_1, priority=0)
        TransitionApprovalMetaFactory.create(workflow=workflow, transition_meta=transition_meta_2, priority=0)

        BasicTestModelObjectFactory()
        TransitionApproval.objects.filter(workflow=workflow).update(status=APPROVED)
        approvals = TransitionApproval.objects.filter(workflow=workflow)
        assert_that(approvals, has_length(2))

        assert_that(
            calling(state2.delete),
            raises(ProtectedError, "Cannot delete some instances of model 'State' because they are referenced through a protected foreign key")
        ) 
Example #29
Source File: test__transition_approval.py    From django-river with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_shouldNotAllowTheStateToBeDeletedWhenThereIsATransitionApprovalThatIsUsedAsDestination(self):
        content_type = ContentType.objects.get_for_model(BasicTestModel)

        state1 = StateObjectFactory(label="state1")
        state2 = StateObjectFactory(label="state2")
        state3 = StateObjectFactory(label="state3")

        workflow = WorkflowFactory(initial_state=state1, content_type=content_type, field_name="my_field")

        transition_meta_1 = TransitionMetaFactory.create(
            workflow=workflow,
            source_state=state1,
            destination_state=state2,
        )

        transition_meta_2 = TransitionMetaFactory.create(
            workflow=workflow,
            source_state=state2,
            destination_state=state3,
        )

        TransitionApprovalMetaFactory.create(workflow=workflow, transition_meta=transition_meta_1, priority=0)
        TransitionApprovalMetaFactory.create(workflow=workflow, transition_meta=transition_meta_2, priority=0)

        BasicTestModelObjectFactory()
        TransitionApproval.objects.filter(workflow=workflow).update(status=APPROVED)
        approvals = TransitionApproval.objects.filter(workflow=workflow)
        assert_that(approvals, has_length(2))

        assert_that(
            calling(state3.delete),
            raises(ProtectedError, "Cannot delete some instances of model 'State' because they are referenced through a protected foreign key")
        ) 
Example #30
Source File: test_delete_protection.py    From donation-tracker with Apache License 2.0 5 votes vote down vote up
def assertDeleteProtected(self, deleted, protected):
        protected.clean()
        with self.assertRaises(ProtectedError):
            deleted.delete()
        protected.delete()