From f16adb23f7d6530af6b88ebf6b58c3b9a8d5b94e Mon Sep 17 00:00:00 2001 From: Kuroshini Date: Mon, 10 Feb 2020 12:43:38 +0300 Subject: [PATCH] catch ForeignKey delete exception on city --- apps/location/views/back.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/apps/location/views/back.py b/apps/location/views/back.py index 774b2dbd..4e23513d 100644 --- a/apps/location/views/back.py +++ b/apps/location/views/back.py @@ -1,5 +1,6 @@ """Location app views.""" from django.contrib.postgres.fields.jsonb import KeyTextTransform +from django.db.models.deletion import ProtectedError from rest_framework import generics, status from rest_framework.response import Response from rest_framework.views import APIView @@ -167,6 +168,13 @@ class CityRUDView(common.CityViewMixin, generics.RetrieveUpdateDestroyAPIView): IsGuest, ) + def delete(self, request, *args, **kwargs): + try: + return self.destroy(request, *args, **kwargs) + except ProtectedError: + from rest_framework.serializers import ValidationError + raise ValidationError({'detail': 'City couldn’t be deleted. Some objects has this city'}) + # Region class RegionListCreateView(common.RegionViewMixin, generics.ListCreateAPIView):