diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index 71005490f3..2307dcae25 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -2252,6 +2252,21 @@ class BinaryField(Field): if self.max_length is not None: self.validators.append(validators.MaxLengthValidator(self.max_length)) + def check(self, **kwargs): + return [*super().check(**kwargs), *self._check_str_default_value()] + + def _check_str_default_value(self): + if self.has_default() and isinstance(self.default, str): + return [ + checks.Error( + "BinaryField's default cannot be a string. Use bytes " + "content instead.", + obj=self, + id='fields.E170', + ) + ] + return [] + def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.editable: diff --git a/docs/ref/checks.txt b/docs/ref/checks.txt index 2e00de454b..117830ffbc 100644 --- a/docs/ref/checks.txt +++ b/docs/ref/checks.txt @@ -159,6 +159,8 @@ Model fields * **fields.W161**: Fixed default value provided. * **fields.W162**: ```` does not support a database index on ```` columns. +* **fields.E170**: ``BinaryField``’s ``default`` cannot be a string. Use bytes + content instead. * **fields.E900**: ``IPAddressField`` has been removed except for support in historical migrations. * **fields.W900**: ``IPAddressField`` has been deprecated. Support for it diff --git a/tests/invalid_models_tests/test_ordinary_fields.py b/tests/invalid_models_tests/test_ordinary_fields.py index a106ab175a..b1a289c977 100644 --- a/tests/invalid_models_tests/test_ordinary_fields.py +++ b/tests/invalid_models_tests/test_ordinary_fields.py @@ -39,6 +39,33 @@ class AutoFieldTests(SimpleTestCase): ]) +@isolate_apps('invalid_models_tests') +class BinaryFieldTests(SimpleTestCase): + + def test_valid_default_value(self): + class Model(models.Model): + field1 = models.BinaryField(default=b'test') + field2 = models.BinaryField(default=None) + + for field_name in ('field1', 'field2'): + field = Model._meta.get_field(field_name) + self.assertEqual(field.check(), []) + + def test_str_default_value(self): + class Model(models.Model): + field = models.BinaryField(default='test') + + field = Model._meta.get_field('field') + self.assertEqual(field.check(), [ + Error( + "BinaryField's default cannot be a string. Use bytes content " + "instead.", + obj=field, + id='fields.E170', + ), + ]) + + @isolate_apps('invalid_models_tests') class CharFieldTests(SimpleTestCase):