Skip to content

Commit

Permalink
Fixed #28431 -- Add system check to prevent string as the default val…
Browse files Browse the repository at this point in the history
…ue for BinaryField.
  • Loading branch information
hramezani committed Mar 17, 2019
1 parent 95b7699 commit f640f41
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
16 changes: 16 additions & 0 deletions django/db/models/fields/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2252,6 +2252,22 @@ def __init__(self, *args, **kwargs):
if self.max_length is not None:
self.validators.append(validators.MaxLengthValidator(self.max_length))

def check(self, **kwargs):
errors = super().check(**kwargs)
errors.extend(self._check_default_is_not_str(**kwargs))
return errors

def _check_default_is_not_str(self, **kwargs):
if self.has_default() and isinstance(self.default, str):
return [
checks.Error(
"BinaryField '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:
Expand Down
2 changes: 2 additions & 0 deletions docs/ref/checks.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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`` ``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
Expand Down
29 changes: 29 additions & 0 deletions tests/invalid_models_tests/test_ordinary_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -700,3 +700,32 @@ class Model(models.Model):
id='fields.W162',
)
])


@isolate_apps('invalid_models_tests')
class BinaryFieldTests(SimpleTestCase):

def test_default_value(self):
class ModelWithDefaultBinaryValue(models.Model):
field = models.BinaryField(default=b'test')

class ModelWithDefaultNoneValue(models.Model):
field = models.BinaryField(default=None)

for Model in (ModelWithDefaultBinaryValue, ModelWithDefaultNoneValue):
with self.subTest(Model=Model):
field = Model._meta.get_field('field')
self.assertEqual(field.check(), [])

def test_default_string(self):
class Model(models.Model):
field = models.BinaryField(default='test')

field = Model._meta.get_field('field')
self.assertEqual(field.check(), [
Error(
"BinaryField 'default' cannot be a string, use bytes content instead.",
obj=field,
id='fields.E170',
),
])

0 comments on commit f640f41

Please sign in to comment.