File tree Expand file tree Collapse file tree 2 files changed +22
-2
lines changed Expand file tree Collapse file tree 2 files changed +22
-2
lines changed Original file line number Diff line number Diff line change @@ -661,7 +661,8 @@ class CharField(Field):
661
661
default_error_messages = {
662
662
'blank' : _ ('This field may not be blank.' ),
663
663
'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.' ),
665
666
}
666
667
initial = ''
667
668
@@ -686,6 +687,9 @@ def run_validation(self, data=empty):
686
687
if not self .allow_blank :
687
688
self .fail ('blank' )
688
689
return ''
690
+ if not isinstance (data , six .string_types + (type (None ), )):
691
+ if data is not empty :
692
+ self .fail ('invalid' , input = data )
689
693
return super (CharField , self ).run_validation (data )
690
694
691
695
def to_internal_value (self , data ):
Original file line number Diff line number Diff line change @@ -501,10 +501,11 @@ class TestCharField(FieldValues):
501
501
Valid and invalid values for `CharField`.
502
502
"""
503
503
valid_inputs = {
504
- 1 : '1' ,
505
504
'abc' : 'abc'
506
505
}
507
506
invalid_inputs = {
507
+ 1 : ['1 is not a valid string.' ],
508
+ 42.0 : ['42.0 is not a valid string.' ],
508
509
'' : ['This field may not be blank.' ]
509
510
}
510
511
outputs = {
@@ -528,6 +529,21 @@ def test_disallow_blank_with_trim_whitespace(self):
528
529
field .run_validation (' ' )
529
530
assert exc_info .value .detail == ['This field may not be blank.' ]
530
531
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
+
531
547
532
548
class TestEmailField (FieldValues ):
533
549
"""
You can’t perform that action at this time.
0 commit comments