9
votes

model.py

class Msg(models.Model):
    content = models.CharField(max_length=1024, null=True)

serializer.py

class MessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Msg
        fields = ["content"]

have data:

{"content": "   space    test    "}

and

print(data)
serializer = MessageSerializer(data=data)
if serializer.is_valid():
    serializer.save()
    print(serializer.data)
    return True, serializer.data
else:
    return False, serializer.errors

first print is {'content': ' space test '} second print is {'content': 'space test'} So the spaces in the database disappeared.
How do I keep spaces?

3
pls remove all the backticksAvinash Raj

3 Answers

17
votes

From DRF docs on CharField:

trim_whitespace - If set to True then leading and trailing whitespace is trimmed. Defaults to True.

So you need to pass this flag to the serializer field yourself and set it to False:

class MessageSerializer(serializers.ModelSerializer):
    content = serializers.CharField(trim_whitespace=False, max_length=1024)
    class Meta:
        model = Msg
        fields = ["content"]

or better via additional keyword arguments:

class MessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Msg
        fields = ["content"]
        extra_kwargs = {"content": {"trim_whitespace": False}}

The second variant is better because the other properties will still be properly picked up from the model by DRF.

1
votes

You can customize the output of that field by implement the method to_representation()

1
votes

You can use trim_whitespace option given in django-rest-framework serializers.

class MessageSerializer(serializers.ModelSerializer):
    content = serializers.CharField(max_length=1024, trim_whitespace=True)

    class Meta:
        model = Msg
        fields = ["content"]