Serializer Validate method removed spaces in password

20 views
Skip to first unread message

mojtaba kamyabi

unread,
Jun 26, 2016, 1:34:15 AM6/26/16
to Django REST framework
here is my code 

class LoginSerializer(serializers.Serializer):
password = serializers.CharField(required=False, style={'input_type': 'password'})

default_error_messages = {
'inactive_account': constants.INACTIVE_ACCOUNT_ERROR,
'invalid_credentials': constants.INVALID_CREDENTIALS_ERROR,
}

def __init__(self, *args, **kwargs):
super(LoginSerializer, self).__init__(*args, **kwargs)
self.user = None
self.fields[User.USERNAME_FIELD] = serializers.CharField(required=False)

def validate(self, attrs):
self.user = authenticate(username=attrs.get(User.USERNAME_FIELD), password=attrs.get('password'))
if self.user:
if not self.user.is_active:
raise serializers.ValidationError(self.error_messages['inactive_account'])
return attrs
else:
raise serializers.ValidationError(self.error_messages['invalid_credentials'])

when my password contains spaces in it `attrs` returns it without spaces and I can login the user (invalid_credentials) how can I fix this problem ?

mojtaba kamyabi

unread,
Jun 26, 2016, 1:36:55 AM6/26/16
to Django REST framework

sorry for typo I mean I CAN'T login the user.

mojtaba kamyabi

unread,
Jun 26, 2016, 1:54:24 AM6/26/16
to Django REST framework
I think I find the problem in rest_framework/fields.py I see this code :
def to_internal_value(self, data):
value = six.text_type(data)
return value.strip() if self.trim_whitespace else value
how can I avoid to strip when `self.trim_whitespace` is True ?

On Sunday, June 26, 2016 at 10:04:15 AM UTC+4:30, mojtaba kamyabi wrote:

Tom Christie

unread,
Jun 27, 2016, 12:42:07 AM6/27/16
to Django REST framework
Use 'trim_whitespace=False' on the serializer field.

(Tho far better would be to *always* trim whitespace both on password creation and check)

mojtaba kamyabi

unread,
Jun 28, 2016, 3:25:16 AM6/28/16
to Django REST framework
thank you now works :) but why it is better to trim it in both creation and check ? is that a security issue ?
Reply all
Reply to author
Forward
0 new messages