Search code examples
pythondjangohttp-status-codes

How to override Django's default response code?


I have two classes in my views.py to handle GET all users, GET one user and POST a new user. If I try to post a user with an id that already exists, Django throws the default 400 - bad request -error. What I'd like to do is send a 409 conflict error instead. How could I achieve this?

I tried and succeeded to get the request when posting new object, but I don't know how to get the response.

These are my classes:

class UserListView(generics.ListCreateAPIView):

    queryset = User.objects.all()

    serializer_class = UserSerializer

    permission_classes = [permissions.AllowAny]



class UserView(generics.RetrieveUpdateDestroyAPIView):

    permission_classes = (permissions.AllowAny)

    queryset = User.objects.all()

    serializer_class = UserSerializer

Solution

  • So I tried to reproduce your problem but it is quite unclear to me what you are trying to accomplish. When doing a POST request you should not specify the ID, because POST is used to create a new element and the ID is automatically created by the backend. This website explains how POST request should be used.

    Anyway, if you want to override the response code, you need to override your view post method like below.

    def post(self, request, *args, **kwargs):
        try:
            return super().post(request, *args, **kwargs)
        except Exception:  # you must find the exact Exception raised here
            return Response(status=409)