Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django REST control serializer does not automatically remove spaces?

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?

like image 435
liansheng Avatar asked Apr 25 '18 09:04

liansheng


3 Answers

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.

like image 193
Kos Avatar answered Oct 08 '22 21:10

Kos


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

like image 20
Hayden Avatar answered Oct 08 '22 21:10

Hayden


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"]
like image 24
Lakhan Avatar answered Oct 08 '22 22:10

Lakhan