Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return custom status code via DRF?

If a user sends a POST request to create a job, but that job already exists - I am trying to return a 202.

Instead, it is returning a 400..

views

def post(self, request, format=None):
    serializer = CreateJobSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializer

class CreateJobSerializer(GenericSerializer):
    class Meta:
        model = Job
        fields = ('name')

    def create(self, validated_data):
        try:
            obj = Job.objects.create(**validated_data)
            return obj
        except:
            return Response(serializer.errors, status=status.HTTP_202_ACCEPTED)

I assume that Job.objects.create will fail if unique=true is violated on that model, if that is the case I would expect a 202 to be returned. What am I doing wrong?

Is it because the unique=true error is actually being caught during validation so create() is never actually called?

like image 945
david Avatar asked Mar 27 '26 13:03

david


1 Answers

I think you can capture the Validation Error and then make a custom response with the status you want (202 in this case).

I haven't tried it but this may work:

try:
    if (serializer.is_valid(raise_exception=True)):
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
except ValidationError as msg:
    if str(msg) == "This Email is already taken":
        return Response(
            {'ValidationError': str(msg)},
            status=status.HTTP_202_ACCEPTED
        )
    else:
        return Response(
            {'ValidationError': str(msg)},
        status=status.HTTP_400_BAD_REQUEST
        )
like image 154
Alberto Avatar answered Mar 30 '26 09:03

Alberto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!