Allamanda Weitgereist
Allamanda Weitgereist

Reputation: 125

getting the IntegrityError Message in Django view

I Have a complex model with 6 constrains and i want to get a message to the user which constrain failed when the post-request fails.

 class testView(APIView):
    @staticmethod
    def post(request):
         serializer = testSerializer(data=request.data)

         if not serializer.is_valid():
             return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

         try:
             testModel.objects.create(
                 # all the data
             )
             return testView.get(request)
         except IntegrityError:
             return Response(status=status.HTTP_403_FORBIDDEN)

The exception is called but I cant find the specific constrain that faild in the IntegrityErrorclass.

Is there any way to return the specific Constrain to the User?

(iam using django 3.0.2 with Postgresql)

Upvotes: 1

Views: 2529

Answers (1)

iklinac
iklinac

Reputation: 15738

Get the actual error message from exception

except IntegrityError as e:
    error_message = e.__cause__

As per PEP 3134, a __cause__ attribute is set with the original (underlying) database exception, allowing access to any additional information provided.

Upvotes: 4

Related Questions