[Answered ]-Using validate filename function in all Django sterilizers

1👍

You can do the following:

class CustomModelSerializer(serializers.ModelSerializer):
    def validate_extension(self, filename):
        extension = os.path.splitext(filename)[1].replace(".", "")
        if extension.lower() not in ALLOWED_IMAGE_EXTENSIONS:
            raise serializers.ValidationError(
            (f'Invalid uploaded file type: {filename}'),
            code='invalid',
        return filename

class ExampleOne(CustomModelSerializer):
    
    class Meta:
        model = ExampleOne
        fields =['']

    def create(self, validated_data):  ...   
        return item
   

0👍

You could have a separate class in which you can have the function you don’t want to repeat. Then you could inherit that class along with ModelSerializer class wherever you need the function, so that you don’t have to repeat yourself.

Leave a comment