Skip to content

Commit c88514f

Browse files
committed
CharField should not accept numbers and collections as valid input
1 parent a67eed1 commit c88514f

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

rest_framework/fields.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -661,7 +661,8 @@ class CharField(Field):
661661
default_error_messages = {
662662
'blank': _('This field may not be blank.'),
663663
'max_length': _('Ensure this field has no more than {max_length} characters.'),
664-
'min_length': _('Ensure this field has at least {min_length} characters.')
664+
'min_length': _('Ensure this field has at least {min_length} characters.'),
665+
'invalid': _('{input} is not a valid string.'),
665666
}
666667
initial = ''
667668

@@ -686,6 +687,9 @@ def run_validation(self, data=empty):
686687
if not self.allow_blank:
687688
self.fail('blank')
688689
return ''
690+
if not isinstance(data, six.string_types + (type(None), )):
691+
if data is not empty:
692+
self.fail('invalid', input=data)
689693
return super(CharField, self).run_validation(data)
690694

691695
def to_internal_value(self, data):

tests/test_fields.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -501,10 +501,11 @@ class TestCharField(FieldValues):
501501
Valid and invalid values for `CharField`.
502502
"""
503503
valid_inputs = {
504-
1: '1',
505504
'abc': 'abc'
506505
}
507506
invalid_inputs = {
507+
1: ['1 is not a valid string.'],
508+
42.0: ['42.0 is not a valid string.'],
508509
'': ['This field may not be blank.']
509510
}
510511
outputs = {
@@ -528,6 +529,21 @@ def test_disallow_blank_with_trim_whitespace(self):
528529
field.run_validation(' ')
529530
assert exc_info.value.detail == ['This field may not be blank.']
530531

532+
def test_collection_types_are_invalid_input(self):
533+
field = serializers.CharField()
534+
input_values = (
535+
42,
536+
{},
537+
[],
538+
tuple(),
539+
set(),
540+
)
541+
for value in input_values:
542+
with pytest.raises(serializers.ValidationError) as exc_info:
543+
field.run_validation(value)
544+
expected = ['{0} is not a valid string.'.format(value)]
545+
assert exc_info.value.detail == expected
546+
531547

532548
class TestEmailField(FieldValues):
533549
"""

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy