Home > Software design >  Trim_whitespace=True is not working in Django Serializer
Trim_whitespace=True is not working in Django Serializer

Time:01-06

I am trying to trim whitespace from API input before writing to DB. I am using

>>> class A(object):
...     def __init__(self, name, email, phone_number):
...             self.name = name
...             self.email = email
...             self.phone_number = phone_number
... 
>>> class ASerializer(serializers.Serializer):
...     name = serializers.CharField(max_length = 200, trim_whitespace=True)
...     email = serializers.EmailField()
...     phone_number = serializers.RegexField("[0-9]{10}")
>>> obj = Geeks("Aditi ", "[email protected]", "1234567890 ")
>>> serializer = ASerializer(obj)
>>> serializer.data
{'name': 'Aditi ', 'email': '[email protected]', 'phone_number': '1234567890 '}

why is it not removing space in name? Any idea?

CodePudding user response:

The way you are checking/using the serializer is not correct. If you want to check if your serializer is working properly, check like this.

>>>serializer = ASerializer(data={"name": "Aditi ", "email": "[email protected]", "phone_number": '1234567890 '})
>>>serializer.is_valid()
True
>>>serializer.validated_data
OrderedDict([('name', 'Aditi'), ('email', '[email protected]'), ('phone_number', '1234567890')])
  • Related