I read and understood in the documentation that it is possible to make custom validations for the model serializer class. However I don’t know how to catch the custom error message. I created the custom error messages and raise them in the validate_request() method in the UserPostSerializer class but the message I include doesn’t go to the serializer.errors in the view method for POST
This is what I’ve brewed up while testing this. It does raise the exception but it doesn’t give me the message which I included in the serializer class:
class UsersAPIview(APIView):
def post(self, request):
mydata = request.data
serializer = UserPostSerializer(data=mydata)
if serializer.is_valid():
try:
#Calling my custom validation method
serializer.validate_request(mydata) #Should raise my custom ValidationError
except ValidationError:
#serializer.errors only works after calling is_valid()
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#I want to return my custom error message here but it's returning an empty dict {} instead.
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
This is the serializer class for the view:
class UserPostSerializer(serializers.ModelSerializer):
class Meta:
model = Users
fields = ['username', 'password']
def validate_request(self, request_data):
"""This is my custom validation method"""
#Validate attributes
list_keys = request_data.keys()
if len(list_keys)!=2:
raise serializers.ValidationError({'Error':'Invalid attributes'})
try:
pw = request_data['password']
usn = request_data['username']
except:
raise serializers.ValidationError({'Error':'Request must have password and username'})
#Custom length validation for testing purposes
if len(pw)<5 or len(usn)<5:
raise serializers.ValidationError({'Error':'Pw and usn must have length <5'})
return
UPDATE:
I’ve resorted to returning integers in the custom validation and storing a dict in the view to access custom errors.