Shirux
Shirux

Reputation: 153

How to remove extra whitespaces on django rest serializers

I have this problem atm where you serializer an object in django and it appears something like that.

{"title": "   remove   all spaces  "}

Within the serializer you can set extra_kwargs to trim fields. The results is the next

{"title": "remove   all spaces"}

Is there a way to remove those extra white spaces between the words "remove" and "all"??

Here is the serializer example:

class exampleSerializer(serializers.ModelSerializer):
  
  class Meta:
     model = Example
     fields = ("title", )
     extra_kwargs = {"content": {"trim_whitespace": True}}

Upvotes: 1

Views: 798

Answers (1)

Zhivko Zaikov
Zhivko Zaikov

Reputation: 449

add to_representation method to your serializer:

    def to_representation(self, data):
        data = super(exampleSerializer, self).to_representation(data)
        content = data['content']
        data['content'] = " ".join(content.split())
        return data

Upvotes: 1

Related Questions