Custom Validator in Django Rest Framework Serializer

Here is how to create your own validator for your serializer fields.
For example I have serializer that it will accept image not large than 20MB.
There are 2 approach for this, we can use function or class based.

class ProfileSerializer(serializers.Serializer):
    profile_pict = serializers.ImageField()

Function based:

def validate_20mb_size(value):
    max_size = 1024 * 1024 * 20  # 20MB
    if value.size > max_size:
        raise serializers.ValidationError('Profile Image too large.')

# Then we use like this.
profile_pict = serializers.ImageField(validators=[validate_20mb_size])

Class based:

class ImageSizeValidator(object):
     def __init__(self, max_size):
        self.max_size = 1024 * 1024 * max_size

     def __call__(self, value):
        if value.size > self.max_size:
            raise serializers.ValidationError('Profile Image too large.')

# Then we use like this.
profile_pict = serializers.ImageField(validators=[ImageSizeValidator(max_size=20)])

You can use whatever you want depend on your needs, but I prefer to use class based because we can use the constructor to make the validator more generic and also inheritance. 😀

Reference: http://www.django-rest-framework.org/api-guide/validators/#writing-custom-validators

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s