From 004ed5936bcfd41cc4999d427da59260ce309f08 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 10 Aug 2016 17:07:22 +0100 Subject: [PATCH] Stricter type validation for CharField --- rest_framework/fields.py | 6 ++++++ tests/test_fields.py | 2 ++ 2 files changed, 8 insertions(+) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 3a2f27205..fab79808f 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -672,6 +672,7 @@ class NullBooleanField(Field): class CharField(Field): default_error_messages = { + 'invalid': _('Not a valid string.'), '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.') @@ -702,6 +703,11 @@ class CharField(Field): return super(CharField, self).run_validation(data) def to_internal_value(self, data): + # We're lenient with allowing basic numerics to be coerced into strings, + # but other types should fail. Eg. unclear if booleans should represent as `true` or `True`, + # and composites such as lists are likely user error. + if isinstance(data, bool) or not isinstance(data, six.string_types + six.integer_types + (float,)): + self.fail('invalid') value = six.text_type(data) return value.strip() if self.trim_whitespace else value diff --git a/tests/test_fields.py b/tests/test_fields.py index 1cbff9909..f1a588c27 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -535,6 +535,8 @@ class TestCharField(FieldValues): 'abc': 'abc' } invalid_inputs = { + (): ['Not a valid string.'], + True: ['Not a valid string.'], '': ['This field may not be blank.'] } outputs = {