本文整理汇总了Python中django.db.models.deletion.ProtectedError方法的典型用法代码示例。如果您正苦于以下问题:Python deletion.ProtectedError方法的具体用法?Python deletion.ProtectedError怎么用?Python deletion.ProtectedError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models.deletion
的用法示例。
在下文中一共展示了deletion.ProtectedError方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: destroy
# 需要导入模块: from django.db.models import deletion [as 别名]
# 或者: from django.db.models.deletion import ProtectedError [as 别名]
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)
示例2: test_playlist_hard_deletion_cascade
# 需要导入模块: from django.db.models import deletion [as 别名]
# 或者: from django.db.models.deletion import ProtectedError [as 别名]
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)
示例3: delete
# 需要导入模块: from django.db.models import deletion [as 别名]
# 或者: from django.db.models.deletion import ProtectedError [as 别名]
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)
示例4: test_visitor_deletion
# 需要导入模块: from django.db.models import deletion [as 别名]
# 或者: from django.db.models.deletion import ProtectedError [as 别名]
def test_visitor_deletion(self):
visitor = VisitorFactory()
PartnershipLeadFactory(visitor=visitor)
with self.assertRaises(ProtectedError):
visitor.delete()
示例5: update_module
# 需要导入模块: from django.db.models import deletion [as 别名]
# 或者: from django.db.models.deletion import ProtectedError [as 别名]
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()
示例6: test_protected_delete
# 需要导入模块: from django.db.models import deletion [as 别名]
# 或者: from django.db.models.deletion import ProtectedError [as 别名]
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())
示例7: test_ticket_22998
# 需要导入模块: from django.db.models import deletion [as 别名]
# 或者: from django.db.models.deletion import ProtectedError [as 别名]
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()
示例8: prevent_deletes
# 需要导入模块: from django.db.models import deletion [as 别名]
# 或者: from django.db.models.deletion import ProtectedError [as 别名]
def prevent_deletes(sender, instance, **kwargs):
raise ProtectedError("Not allowed to delete.", [instance])
示例9: test_no_delete_pod_pool
# 需要导入模块: from django.db.models import deletion [as 别名]
# 或者: from django.db.models.deletion import ProtectedError [as 别名]
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)
示例10: exception_handler
# 需要导入模块: from django.db.models import deletion [as 别名]
# 或者: from django.db.models.deletion import ProtectedError [as 别名]
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