Fixed #28431 -- Added a system check for BinaryField to prevent strings defaults.

Thanks Claude Paroz for the initial patch.
This commit is contained in:
Hasan Ramezani 2019-03-17 21:47:21 +01:00 committed by Mariusz Felisiak
parent dc53f2135b
commit 981dd6dd71
No known key found for this signature in database
GPG Key ID: 2EF56372BA48CD1B
3 changed files with 44 additions and 0 deletions

View File

@ -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:

View File

@ -159,6 +159,8 @@ Model fields
* **fields.W161**: Fixed default value provided.
* **fields.W162**: ``<database>`` does not support a database index on
``<field data type>`` 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

View File

@ -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):