Django-rest-framework: serializers.ValidationError

Created on 1 Apr 2019  路  2Comments  路  Source: encode/django-rest-framework

Steps to reproduce

While trying to raise a rest_framework.serializers.ValidationError, I noticed that the following code does not change the status_code

raise serializers.ValidationError('An error', code=HTTP_404_NOT_FOUND)

After some checks, however, I found that I had to do

api_exception = serializers.ValidationError(err_obj)
api_exception.status_code = HTTP_404_NOT_FOUND
raise api_exception

I just wanted to suggest that we add the status_code property to the ValidationError as this is more intuitive. What do you think

Expected Behaviour

The following ought to change the status code to 404

raise serializers.ValidationError('An error', status_code=HTTP_404_NOT_FOUND)

All 2 comments

Why don't you just use NotFound?

I don't think this is behavior we want to support, and I don't think the fix will function like you expect. Serializer errors are collected and re-raised under a new ValidationError instance, so your provided status_code wouldn't be used by the exception handler.

https://github.com/encode/django-rest-framework/blob/1ac0f63aa9a6ceed5e4221926929117528af2714/rest_framework/serializers.py#L243-L244

To get custom status codes to work, the exception handler would need to have special handling that walks the validation errors, collecting all status_codes, then determine which one to use. e.g., if you have a combination of 400's and 404's, your handler would need to somehow determine which status code should be raised.


If you do want to proceed with this, I would recommend creating a custom ValidationError subclass that sets its own status code, then write an exception handler that does whatever you'd expect it to do.

class MyValidationError(serializers.ValidationError):
    status_code = 404
Was this page helpful?
0 / 5 - 0 ratings