How to write custom validations on drf. I have validate function on serializer. Can someone help whats wrong with my code? my views:
class MyCustomView(ListCreateAPIView):
def create(self, request, *args, **kwargs):
serializer = MyCustomSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
my serializer:
class MyCustomView(serializers.Serializer):
name = serializers.CharField(required=True, max_length=64)
address = serializers.CharField(required=True, max_length=64)
def validate(self, attrs):
if not attrs.get('name'):
raise serializers.ValidationError('Name field is required.')
when i request with blank name and address it shows default drf error. How to override this function?
CodePudding user response:
remove required=True from both of your fields.
but it's better you don't bother your backend with empty data and have your frontend handle it.
CodePudding user response:
You forgot to return attrs after validation.
def validate(self, attrs):
if not attrs.get('name'):
raise serializers.ValidationError('Name field is required.')
return attrs