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?
From the DRF doc of ParseError
ParseError
Raised if the request contains malformed data when accessingrequest.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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With