diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index c64535ff99..3354bf6edf 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -1963,7 +1963,12 @@ class GenericIPAddressField(Field): return "GenericIPAddressField" def to_python(self, value): - if value and ':' in value: + if value is None: + return None + if not isinstance(value, six.string_types): + value = force_text(value) + value = value.strip() + if ':' in value: return clean_ipv6_address(value, self.unpack_ipv4, self.error_messages['invalid']) return value diff --git a/tests/validation/tests.py b/tests/validation/tests.py index 693d6b6c23..653a6b1c4c 100644 --- a/tests/validation/tests.py +++ b/tests/validation/tests.py @@ -3,6 +3,7 @@ from __future__ import unicode_literals from django import forms from django.core.exceptions import NON_FIELD_ERRORS from django.test import TestCase +from django.utils.functional import lazy from . import ValidationTestCase from .models import ( @@ -129,6 +130,10 @@ class GenericIPAddressFieldTests(ValidationTestCase): def test_correct_generic_ip_passes(self): giptm = GenericIPAddressTestModel(generic_ip="1.2.3.4") self.assertIsNone(giptm.full_clean()) + giptm = GenericIPAddressTestModel(generic_ip=" 1.2.3.4 ") + self.assertIsNone(giptm.full_clean()) + giptm = GenericIPAddressTestModel(generic_ip="1.2.3.4\n") + self.assertIsNone(giptm.full_clean()) giptm = GenericIPAddressTestModel(generic_ip="2001::2") self.assertIsNone(giptm.full_clean()) @@ -137,6 +142,10 @@ class GenericIPAddressFieldTests(ValidationTestCase): self.assertFailsValidation(giptm.full_clean, ['generic_ip']) giptm = GenericIPAddressTestModel(generic_ip="1:2") self.assertFailsValidation(giptm.full_clean, ['generic_ip']) + giptm = GenericIPAddressTestModel(generic_ip=1) + self.assertFailsValidation(giptm.full_clean, ['generic_ip']) + giptm = GenericIPAddressTestModel(generic_ip=lazy(lambda: 1, int)) + self.assertFailsValidation(giptm.full_clean, ['generic_ip']) def test_correct_v4_ip_passes(self): giptm = GenericIPAddressTestModel(v4_ip="1.2.3.4")