diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index f9ae55f844f..3351b4ad35d 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -1069,11 +1069,7 @@ class CharField(Field): return errors def _check_max_length_attribute(self, **kwargs): - try: - max_length = int(self.max_length) - if max_length <= 0: - raise ValueError() - except TypeError: + if self.max_length is None: return [ checks.Error( "CharFields must define a 'max_length' attribute.", @@ -1082,7 +1078,7 @@ class CharField(Field): id='fields.E120', ) ] - except ValueError: + elif not isinstance(self.max_length, six.integer_types) or self.max_length <= 0: return [ checks.Error( "'max_length' must be a positive integer.", diff --git a/tests/invalid_models_tests/test_ordinary_fields.py b/tests/invalid_models_tests/test_ordinary_fields.py index c98d218b091..9baaf70feba 100644 --- a/tests/invalid_models_tests/test_ordinary_fields.py +++ b/tests/invalid_models_tests/test_ordinary_fields.py @@ -129,6 +129,22 @@ class CharFieldTests(IsolatedModelsTestCase): ] self.assertEqual(errors, expected) + def test_str_max_length_value(self): + class Model(models.Model): + field = models.CharField(max_length='20') + + field = Model._meta.get_field('field') + errors = field.check() + expected = [ + Error( + "'max_length' must be a positive integer.", + hint=None, + obj=field, + id='fields.E121', + ), + ] + self.assertEqual(errors, expected) + def test_non_iterable_choices(self): class Model(models.Model): field = models.CharField(max_length=10, choices='bad')