Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use ParseError versus ValidationError in Django Rest Framework serializer?

With Django Rest Framework, when should I be raising a ParseError versus a serializers.ValidationError when validating form data in a serializer?

My code looks something like this:

class UserSerializer(serializers.ModelSerializer):
    def create(self, validated_data):
        if  'username' not in validated_data:
            raise ParseError({'username': ['A username is required.']})
        if  'password' not in validated_data:
            raise ParseError({'password': ['A password is required.']})
        if  'email' not in validated_data or len(validated_data['email']) == 0:
            raise ParseError({'email': ['An email is required.']})
        if UserModel.objects.filter(email=validated_data['email']):
            raise ParseError({'email': ['A user with that email already exists.']})

        # ...

Which of these, if any, should be serializers.ValidationError instead? And what rule should I follow in the future to determine which to use?

like image 730
personjerry Avatar asked Mar 16 '26 14:03

personjerry


1 Answers

From the DRF doc of ParseError

ParseError
Raised if the request contains malformed data when accessing request.data.

Usually, this is handled by DRF itself. So, you don't have to explicitly raise it. In your case, all of the conditions are comes under ValidationError section. So, it would be more appropriate to use the ValidationError rather than the ParseError.


NOTE: It's highly reccomend to use the validate(...) method for object-level validation and validate_<field_name>(...) method for field-level validation in Django RESTFramework. (It's not good to handle validation in create or any other methods, in DRF)

like image 50
JPG Avatar answered Mar 18 '26 04:03

JPG