Python django.db.models.deletion.ProtectedError() Examples

The following are 16 code examples of django.db.models.deletion.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.deletion , or try the search function .
Example #1
Source File: views.py    From controller with MIT License 6 votes vote down vote up
def destroy(self, request, **kwargs):
        calling_obj = self.get_object()
        target_obj = calling_obj

        if request.data.get('username'):
            # if you "accidentally" target yourself, that should be fine
            if calling_obj.username == request.data['username'] or calling_obj.is_superuser:
                target_obj = get_object_or_404(User, username=request.data['username'])
            else:
                raise PermissionDenied()

        # A user can not be removed without apps changing ownership first
        if len(models.App.objects.filter(owner=target_obj)) > 0:
            msg = '{} still has applications assigned. Delete or transfer ownership'.format(str(target_obj))  # noqa
            raise AlreadyExists(msg)

        try:
            target_obj.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except ProtectedError as e:
            raise AlreadyExists(e) 
Example #2
Source File: test_models_deletion.py    From marsha with MIT License 6 votes vote down vote up
def test_playlist_hard_deletion_cascade(self):
        """It should not be possible to hard delete a playlist that still contains videos."""
        organization = OrganizationFactory()
        user = UserFactory()
        playlist = PlaylistFactory(organization=organization, created_by=user)

        video = VideoFactory(created_by=user, playlist=playlist)
        copied_playlist = PlaylistFactory(
            organization=organization, created_by=user, duplicated_from=playlist
        )
        playlist_access = PlaylistAccessFactory(user=user, playlist=playlist)

        with self.assertRaises(ProtectedError):
            playlist.delete(force_policy=HARD_DELETE)

        self.assertIsVisible(playlist)
        self.assertIsVisible(video)
        self.assertIsVisible(copied_playlist)
        self.assertIsVisible(playlist_access) 
Example #3
Source File: views.py    From controller with MIT License 6 votes vote down vote up
def destroy(self, request, **kwargs):
        calling_obj = self.get_object()
        target_obj = calling_obj

        if request.data.get('username'):
            # if you "accidentally" target yourself, that should be fine
            if calling_obj.username == request.data['username'] or calling_obj.is_superuser:
                target_obj = get_object_or_404(User, username=request.data['username'])
            else:
                raise PermissionDenied()

        # A user can not be removed without apps changing ownership first
        if len(models.App.objects.filter(owner=target_obj)) > 0:
            msg = '{} still has applications assigned. Delete or transfer ownership'.format(str(target_obj))  # noqa
            raise AlreadyExists(msg)

        try:
            target_obj.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except ProtectedError as e:
            raise AlreadyExists(e) 
Example #4
Source File: views_resource.py    From boss with Apache License 2.0 5 votes vote down vote up
def delete(self, request, collection):
        """
        Delete a collection
        Args:
            request: DRF Request object
            collection:  Name of collection to delete
        Returns:
            Http status
        """
        try:
            collection_obj = Collection.objects.get(name=collection)

            if request.user.has_perm("delete", collection_obj):

                # Are there experiments that reference it
                serializer = CollectionSerializer(collection_obj)
                if len(serializer.get_experiments(collection_obj)) > 0:
                    # This collection has experiments that reference it and cannot be deleted
                    return BossHTTPError("Collection {} has experiments that reference it and cannot be deleted."
                                         "Please delete the experiments first.".format(collection),
                                         ErrorCodes.INTEGRITY_ERROR)

                collection_obj.to_be_deleted = datetime.now()
                collection_obj.save()

                return HttpResponse(status=204)
            else:
                return BossPermissionError('delete', collection)
        except Collection.DoesNotExist:
            return BossResourceNotFoundError(collection)
        except ProtectedError:
            return BossHTTPError("Cannot delete {}. It has experiments that reference it.".format(collection),
                                 ErrorCodes.INTEGRITY_ERROR) 
Example #5
Source File: views_resource.py    From boss with Apache License 2.0 5 votes vote down vote up
def delete(self, request, coordframe):
        """
        Delete a coordinate frame
        Args:
            request: DRF Request object
            coordframe:  Name of coordinateframe to delete
        Returns:
            Http status
        """
        try:
            coordframe_obj = CoordinateFrame.objects.get(name=coordframe)

            if request.user.has_perm("delete", coordframe_obj):
                # Are there experiments that reference it
                serializer = CoordinateFrameDeleteSerializer(coordframe_obj)
                if len(serializer.get_valid_exps(coordframe_obj)) > 0:
                    # This collection has experiments that reference it and cannot be deleted
                    return BossHTTPError(" Coordinate frame {} has experiments that reference it and cannot be deleted."
                                         "Please delete the experiments first.".format(coordframe),
                                         ErrorCodes.INTEGRITY_ERROR)

                coordframe_obj.to_be_deleted = datetime.now()
                coordframe_obj.save()
                return HttpResponse(status=204)
            else:
                return BossPermissionError('delete', coordframe)
        except CoordinateFrame.DoesNotExist:
            return BossResourceNotFoundError(coordframe)
        except ProtectedError:
            return BossHTTPError("Cannot delete {}. It has experiments that reference it.".format(coordframe),
                                 ErrorCodes.INTEGRITY_ERROR) 
Example #6
Source File: views_resource.py    From boss with Apache License 2.0 5 votes vote down vote up
def delete(self, request, collection, experiment):
        """
        Delete a experiment
        Args:
            request: DRF Request object
            collection:  Name of collection
            experiment: Experiment name to delete
        Returns:
            Http status
        """
        try:
            collection_obj = Collection.objects.get(name=collection)
            experiment_obj = Experiment.objects.get(name=experiment, collection=collection_obj)
            if request.user.has_perm("delete", experiment_obj):
                # Are there channels that reference it
                serializer = ExperimentReadSerializer(experiment_obj)
                if len(serializer.get_channels(experiment_obj)) > 0:
                    # This experiment has channels that reference it and cannot be deleted
                    return BossHTTPError(" Experiment {} has channels that reference it and cannot be deleted."
                                         "Please delete the channels first.".format(experiment),
                                         ErrorCodes.INTEGRITY_ERROR)

                experiment_obj.to_be_deleted = datetime.now()
                experiment_obj.save()

                return HttpResponse(status=204)
            else:
                return BossPermissionError('delete', experiment)
        except Collection.DoesNotExist:
            return BossResourceNotFoundError(collection)
        except Experiment.DoesNotExist:
            return BossResourceNotFoundError(experiment)
        except ProtectedError:
            return BossHTTPError("Cannot delete {}. It has channels that reference it."
                                 .format(experiment), ErrorCodes.INTEGRITY_ERROR) 
Example #7
Source File: views_resource.py    From boss with Apache License 2.0 5 votes vote down vote up
def delete(self, request, collection, experiment, channel):
        """
        Delete a Channel
        Args:
            request: DRF Request object
            collection: Collection name
            experiment: Experiment name
            channel: Channel name

        Returns :
            Http status
        """
        try:
            collection_obj = Collection.objects.get(name=collection)
            experiment_obj = Experiment.objects.get(name=experiment, collection=collection_obj)
            channel_obj = Channel.objects.get(name=channel, experiment=experiment_obj)

            if request.user.has_perm("delete", channel_obj):

                # The channel cannot be deleted if this is the source of any other channels
                derived_channels = channel_obj.get_derived()
                if len(derived_channels) > 0:
                    return BossHTTPError("Channel {} is the source channel of other channels and cannot be deleted"
                                         .format(channel), ErrorCodes.INTEGRITY_ERROR)
                channel_obj.to_be_deleted = datetime.now()
                channel_obj.save()
                return HttpResponse(status=204)
            else:
                return BossPermissionError('delete', channel)

        except Collection.DoesNotExist:
            return BossResourceNotFoundError(collection)
        except Experiment.DoesNotExist:
            return BossResourceNotFoundError(experiment)
        except Channel.DoesNotExist:
            return BossResourceNotFoundError(channel)
        except ProtectedError:
            return BossHTTPError("Cannot delete {}. It has channels that reference it.".format(channel),
                                 ErrorCodes.INTEGRITY_ERROR) 
Example #8
Source File: test_models.py    From intake with MIT License 5 votes vote down vote up
def test_visitor_deletion(self):
        visitor = VisitorFactory()
        PartnershipLeadFactory(visitor=visitor)
        with self.assertRaises(ProtectedError):
            visitor.delete() 
Example #9
Source File: app_loading.py    From govready-q with GNU General Public License v3.0 5 votes vote down vote up
def update_module(m, spec, log_status):
    # Update a module instance according to the specification data.
    # See is_module_changed.
    if log_status:
        print("Updating", repr(m), file=sys.stderr)

    # Remove the questions from the module spec because they'll be
    # stored with the ModuleQuestion instances.
    m.visible = True
    m.spec = remove_questions(spec)
    m.save()

    # Update its questions.
    qs = set()
    for i, question in enumerate(spec.get("questions", [])):
        qs.add(update_question(m, i, question, log_status))

    # Delete removed questions (only happens if the Module is
    # not yet in use).
    for q in m.questions.all():
        if q not in qs:
            if log_status:
                print("Deleting", repr(q), file=sys.stderr)
            try:
                q.delete()
            except ProtectedError:
                raise IncompatibleUpdate("Module {} cannot be updated because question {}, which has been removed, has already been answered.".format(m.module_name, q.key))

    # If we're updating a Module in-place, clear out any cached state on its Tasks.
    for t in Task.objects.filter(module=m):
        t.on_answer_changed() 
Example #10
Source File: test_models.py    From cleanerversion with Apache License 2.0 5 votes vote down vote up
def test_protected_delete(self):
        WizardFan.objects.create(name="Gandalf", team=self.team)
        # The wizard does his best to protect his team and it's city.
        # (on_delete=PROTECTED)
        with self.assertRaises(ProtectedError):
            self.city.delete()
        self.assertEqual(1,
                         Team.objects.current.filter(pk=self.team.pk).count())
        self.assertEqual(1,
                         City.objects.current.filter(pk=self.city.pk).count()) 
Example #11
Source File: tests.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_ticket_22998(self):
        related = Related.objects.create()
        content = Content.objects.create(related_obj=related)
        Node.objects.create(content=content)

        # deleting the Related cascades to the Content cascades to the Node,
        # where the pre_delete signal should fire and prevent deletion.
        with self.assertRaises(ProtectedError):
            related.delete() 
Example #12
Source File: models.py    From django-sqlserver with MIT License 5 votes vote down vote up
def prevent_deletes(sender, instance, **kwargs):
    raise ProtectedError("Not allowed to delete.", [instance]) 
Example #13
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_ticket_22998(self):
        related = Related.objects.create()
        content = Content.objects.create(related_obj=related)
        Node.objects.create(content=content)

        # deleting the Related cascades to the Content cascades to the Node,
        # where the pre_delete signal should fire and prevent deletion.
        with self.assertRaises(ProtectedError):
            related.delete() 
Example #14
Source File: models.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def prevent_deletes(sender, instance, **kwargs):
    raise ProtectedError("Not allowed to delete.", [instance]) 
Example #15
Source File: test_bmc.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_no_delete_pod_pool(self):
        pool = factory.make_ResourcePool()
        pod = Pod(power_type="virsh", power_parameters={}, pool=pool)
        pod.save()
        self.assertRaises(ProtectedError, pool.delete) 
Example #16
Source File: handlers.py    From product-definition-center with MIT License 4 votes vote down vote up
def exception_handler(exc, context):
    """
    This handler will overwrite rest framework default handler, additionally,
    it will process ValidationError (most of them were raised by
    django.db.models and django.forms), DB error (Refs PEP249).

    Show some details about the error, if it's safe. It could be more useful
    when the server does not work well in production env.

    Setting the `exception` attribute on the response is not necessary as it
    will be done by REST Framework.
    """
    response = views.exception_handler(exc, context)

    if response is None:
        if isinstance(exc, (exceptions.ValidationError, exceptions.FieldError)):
            # value is not correct or name is invalid.
            msg = exc.messages if hasattr(exc, 'messages') else str(exc)
            return Response({'detail': msg},
                            status=status.HTTP_400_BAD_REQUEST)
        elif isinstance(exc, exceptions.ObjectDoesNotExist):
            return Response({'detail': 'Not found:  %s' % str(exc)},
                            status=status.HTTP_404_NOT_FOUND)
        elif isinstance(exc, ProtectedError):
            return Response({"detail": "%s %s" % exc.args},
                            status=status.HTTP_400_BAD_REQUEST)
        elif isinstance(exc, ValueError):
            return Response({'detail': str(exc)},
                            status=status.HTTP_400_BAD_REQUEST)
        elif isinstance(exc, db.IntegrityError):
            # Refs PEP249
            # Maybe a duplicate PK, FK check fails, index conflict.
            return Response({'detail': str(exc)},
                            status=status.HTTP_409_CONFLICT)
        elif isinstance(exc, db.DatabaseError):
            # Refs PEP249
            # Other DB errors, such as incorrect grammar, transaction error etc.
            return Response({'detail': 'The database encountered an internal '
                                       'error or misconfiguration and was '
                                       'unable to complete your request.'},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            logger = logging.getLogger(__name__)
            logger.error('Unhandled exception', exc_info=sys.exc_info())
            return Response(data=settings.INTERNAL_SERVER_ERROR_RESPONSE,
                            status=status.HTTP_503_SERVICE_UNAVAILABLE)
    return response