1

I've read a LOT of topics on validation yet I have no idea why this doesn't work. For example when width = 20 object still passes validation.

So I have this serializer:

class ImageUploadSerializer(serializers.ModelSerializer): 

    picture = Base64ImageField()

    class Meta:
        model = ImageUpload
        fields = ['id', 'url', 'picture']

    def validate_width(self, value):
        if value < 100:
            raise serializers.ValidationError('Width shouldn\'t be less then 100')
        return value

    def create(self, validated_data):
        im = Image.open(validated_data['picture'])
        width, height = im.size
        validated_data['name'] = f'{datetime.datetime.now()}'
        validated_data['width'] = width
        validated_data['height'] = height
        return super().create(validated_data)

And here's my view:

class ResizeImageView(APIView):
    serializer_class = ImageResizeSerializer

    def post(self, request, *args, **kwargs):
        width = request.data['width'] 
        height = request.data['height']
        with open('c:/Users/KK/Desktop/tiny-kitten-in-sunlight.jpg', 'rb') as img:
            mock_resized_obj = img.read()
            mock_resized_obj_64 = pybase64.b64encode_as_string(mock_resized_obj)

        serializer = ImageUploadSerializer(

                    data={'picture': mock_resized_obj_64,
                          'width': width, 
                          'height': height}
        )

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I know it is sloppy and all i just wanna know why validation doesn't work? I use one serializer to get parametres and another one to save and return data.

serializer I use to get parametres is:

class ImageResizeSerializer(serializers.Serializer):
    width = serializers.IntegerField()
    height = serializers.IntegerField()

Thank you beforehand!

1 Answer 1

1

You can add the width field in the ImageUploadSerializer , you don't need another serializer to validate.

class ImageUploadSerializer(serializers.ModelSerializer): 

    picture = Base64ImageField()
    width = serializers.IntegerField()
    height = serializers.IntegerField()

    class Meta:
        model = ImageUpload
        fields = ['id', 'url', 'picture' , 'width' , 'height']

    def validate_width(self, value):
        if value < 100:
            raise serializers.ValidationError('Width shouldn\'t be less then 100')
        return value

    def create(self, validated_data):
        im = Image.open(validated_data['picture'])
        width, height = im.size
        validated_data['name'] = f'{datetime.datetime.now()}'
        validated_data['width'] = width
        validated_data['height'] = height
        return super().create(validated_data)

Its not validating because the ImageResizeSerializer missing the validation method, on the other hand ImageUploadSerializer was missing the field.

Sign up to request clarification or add additional context in comments.

5 Comments

Hello! Yes, that's what i thought as well, I've tried it but it doesn't work. It doesn't see this validation check. Mayby I should override some other methods in Serializer as well?
Based on documentation this should have worked. Docs : django-rest-framework.org/api-guide/serializers , You can debug and check if the validation functions you wrote are actually being called on your expectations.
yeah, I've tried to debug it with prints and it is not being called ever. I've read documentation a dozens times already, maybe I am missing something not sure. Anyways thank you for your help!
I have updated the answer. Take a look if this one works.
Yea, this works great! The problem is, I am not quite sure how to explain: I need ImageUploadSerializer to only show one field and it is the picture field and I use it for uploading the picture. I am using ImageResizeSerializer for another endpoint /images/<id>/resize format in which I resize the image.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.