CharField should not accept numbers and collections as valid input

This commit is contained in:
Steven Loria 2015-09-11 23:52:32 -04:00
parent a67eed1466
commit d345256af4
2 changed files with 22 additions and 2 deletions

View File

@ -661,7 +661,8 @@ class CharField(Field):
default_error_messages = {
'blank': _('This field may not be blank.'),
'max_length': _('Ensure this field has no more than {max_length} characters.'),
'min_length': _('Ensure this field has at least {min_length} characters.')
'min_length': _('Ensure this field has at least {min_length} characters.'),
'invalid': _('{input} is not a valid string.'),
}
initial = ''
@ -686,6 +687,9 @@ class CharField(Field):
if not self.allow_blank:
self.fail('blank')
return ''
if not isinstance(data, (six.text_type, six.binary_type, type(None))):
if data is not empty:
self.fail('invalid', input=data)
return super(CharField, self).run_validation(data)
def to_internal_value(self, data):

View File

@ -501,10 +501,11 @@ class TestCharField(FieldValues):
Valid and invalid values for `CharField`.
"""
valid_inputs = {
1: '1',
'abc': 'abc'
}
invalid_inputs = {
1: ['1 is not a valid string.'],
42.0: ['42.0 is not a valid string.'],
'': ['This field may not be blank.']
}
outputs = {
@ -528,6 +529,21 @@ class TestCharField(FieldValues):
field.run_validation(' ')
assert exc_info.value.detail == ['This field may not be blank.']
def test_collection_types_are_invalid_input(self):
field = serializers.CharField()
input_values = (
42,
{},
[],
tuple(),
set(),
)
for value in input_values:
with pytest.raises(serializers.ValidationError) as exc_info:
field.run_validation(value)
expected = ['{0} is not a valid string.'.format(value)]
assert exc_info.value.detail == expected
class TestEmailField(FieldValues):
"""