Home > Enterprise >  Using validate filename function in all Django sterilizers
Using validate filename function in all Django sterilizers

Time:04-16

I have a validate_filename function in a serializer but seems like I have to use the same function inside multiple serializer classes to validate the file name. It doesn't seem good because it seems redundant and the concept of DRY is not being implemented.

For eg:

class ExampleOne(serializers.ModelSerializer):
    
    class Meta:
        model = ExampleOne
        fields =['']

    def create(self, validated_data):  ...   
        return item
    
    def validate_extension(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',

Now, I have to use the same function inside other serializers class inside the same serializer file and don't want to repeat the same code again. Is there any way we can use a separate file like validatefile.py and import the function only inside the serializer class?? But dont really know how to start and go about it.

CodePudding user response:

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.

CodePudding user response:

You can do the following:

class CustomModelSerializer(serializers.ModelSerializer):
    def validate_filename(self, filename):
        # validate filename here.. 
        return filename

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

    def create(self, validated_data):  ...   
        return item
    
    def validate_extension(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',
  • Related