1

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)

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

if I do this i get this error: AttributeError: type object 'IntegrityError' has no attribute 'message' did you tried it yourself?
It depends on version of python/django sorry pasted old one, now it is in args[0] or just use _cause_ as per PEP 3134
If you're going to check for a substring in __cause__, you need to stringify it, so maybe use error_message = str(e.__cause__). But I think error_message = e.args[0] is cleaner.
e.args[0] could raise index error in cases there is no exception message, to be frank I am not having a particular example of it happening for this use case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.