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?
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.
You can customize the output of that field by implement the method to_representation()
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With