Skip to content

Commit

Permalink
Fixed #28431 -- Added a system check for BinaryField to prevent strin…
Browse files Browse the repository at this point in the history
…gs defaults.

Thanks Claude Paroz for the initial patch.
  • Loading branch information
hramezani authored and felixxm committed Mar 25, 2019
1 parent cbf7e71 commit e4b3ccf
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
15 changes: 15 additions & 0 deletions django/db/models/fields/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2252,6 +2252,21 @@ def __init__(self, *args, **kwargs):
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:
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``’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
Expand Down
27 changes: 27 additions & 0 deletions tests/invalid_models_tests/test_ordinary_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,33 @@ class Model(models.Model):
])


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

Expand Down

0 comments on commit e4b3ccf

Please sign in to comment.