Python django.db.models.ProtectedError() Examples

The following are 30 code examples for showing how to use django.db.models.ProtectedError(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: Servo   Author: fpsw   File: product.py    License: 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
Project: Servo   Author: fpsw   File: device.py    License: 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
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
Project: zing   Author: evernote   File: models.py    License: 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 5
Project: loom   Author: StanfordBioinformatics   File: templates.py    License: 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 6
Project: hypha   Author: OpenTechFund   File: views.py    License: 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 7
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 8
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 9
Project: donation-tracker   Author: GamesDoneQuick   File: test_delete_protection.py    License: 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() 
Example 10
Project: StormOnline   Author: stormsha   File: util.py    License: 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 11
Project: GTDWeb   Author: lanbing510   File: utils.py    License: GNU General Public License v2.0 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 12
Project: bioforum   Author: reBiocoder   File: utils.py    License: 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().collect(objs, source_attr=source_attr, **kwargs)
        except models.ProtectedError as e:
            self.protected.update(e.protected_objects) 
Example 13
Project: wagtail-personalisation   Author: wagtail   File: test_models.py    License: MIT License 5 votes vote down vote up
def test_canonical_page_deletion_is_protected(segmented_page):
    # When deleting canonical page without deleting variants, it should return
    # an error. All variants should be deleted beforehand.
    with pytest.raises(ProtectedError):
        segmented_page.personalisation_metadata.canonical_page.delete() 
Example 14
Project: wagtail-personalisation   Author: wagtail   File: test_models.py    License: MIT License 5 votes vote down vote up
def test_page_protection_when_deleting_segment(segmented_page):
    segment = segmented_page.personalisation_metadata.segment
    assert len(segment.get_used_pages())
    with pytest.raises(ProtectedError):
        segment.delete() 
Example 15
Project: weibo-analysis-system   Author: Superbsco   File: util.py    License: MIT License 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
Project: opencraft   Author: open-craft   File: openedx_monitoring.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def delete(self, *args, **kwargs):  # pylint: disable=arguments-differ
        """
        Delete this email notification channel.
        """
        if not self.shared:
            newrelic.delete_email_notification_channel(self.id)
            super().delete(*args, **kwargs)
        else:
            raise ProtectedError('Cannot delete a shared email notification channel', self) 
Example 17
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 18
Project: django-freeradius   Author: openwisp   File: models.py    License: 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 19
Project: django-freeradius   Author: openwisp   File: test_models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_delete_default_group(self):
        group = self.radius_group_model.objects.get(default=1)
        try:
            group.delete()
        except ProtectedError:
            pass
        else:
            self.fail('ProtectedError not raised') 
Example 20
Project: myblog   Author: myminwang   File: util.py    License: 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 21
Project: CTF_AWD_Platform   Author: xuchaoa   File: util.py    License: MIT License 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
Project: django_OA   Author: abaoMAO   File: util.py    License: 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 as e:
            self.protected.update(e.protected_objects) 
Example 23
Project: zing   Author: evernote   File: api.py    License: GNU General Public License v3.0 5 votes vote down vote up
def delete(self, request, *args, **kwargs):
        """Delete the model and return its JSON representation."""
        if self.pk_field_name not in kwargs:
            return self.status_msg(
                "DELETE is not supported for collections", status=405
            )

        obj = self.get_object()
        try:
            obj.delete()
            return JsonResponse({})
        except ProtectedError as e:
            return self.status_msg(str(e), status=405) 
Example 24
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: utils.py    License: 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().collect(objs, source_attr=source_attr, **kwargs)
        except models.ProtectedError as e:
            self.protected.update(e.protected_objects) 
Example 25
Project: wagtail   Author: wagtail   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        try:
            msg = _("%(model_name)s '%(instance)s' deleted.") % {
                'model_name': self.verbose_name, 'instance': self.instance
            }
            self.delete_instance()
            messages.success(request, msg)
            return redirect(self.index_url)
        except models.ProtectedError:
            linked_objects = []
            fields = self.model._meta.fields_map.values()
            fields = (obj for obj in fields if not isinstance(
                obj.field, ManyToManyField))
            for rel in fields:
                if rel.on_delete == models.PROTECT:
                    if isinstance(rel, OneToOneRel):
                        try:
                            obj = getattr(self.instance, rel.get_accessor_name())
                        except ObjectDoesNotExist:
                            pass
                        else:
                            linked_objects.append(obj)
                    else:
                        qs = getattr(self.instance, rel.get_accessor_name())
                        for obj in qs.all():
                            linked_objects.append(obj)
            context = self.get_context_data(
                protected_error=True,
                linked_objects=linked_objects
            )
            return self.render_to_response(context) 
Example 26
Project: django-leonardo   Author: django-leonardo   File: admin_utils.py    License: BSD 3-Clause "New" or "Revised" 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 27
Project: python   Author: Yeah-Kun   File: utils.py    License: Apache License 2.0 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 28
Project: openhgsenti   Author: drexly   File: utils.py    License: Apache License 2.0 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 29
Project: loom   Author: StanfordBioinformatics   File: views.py    License: 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 30
Project: loom   Author: StanfordBioinformatics   File: runs.py    License: 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()