Skip to content

Commit 8ccb8e5

Browse files
committed
Strip scopes on IPv6Interface instances
1 parent 58afe44 commit 8ccb8e5

2 files changed

Lines changed: 17 additions & 1 deletion

File tree

netfields/fields.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from django.core.exceptions import ValidationError
22
from django.db import models
33

4-
from ipaddress import ip_interface, ip_network
4+
from ipaddress import ip_interface, ip_network, IPv6Interface
55
from netaddr import EUI
66
from netaddr.core import AddrFormatError
77

@@ -159,6 +159,16 @@ def to_python(self, value):
159159
return value.ip
160160
return value
161161

162+
def get_prep_value(self, value):
163+
if not value:
164+
return None
165+
166+
value = self.to_python(value)
167+
# Strip IPv6 scope identifier if it is present
168+
if getattr(value, 'scope_id', None):
169+
value = IPv6Interface((value.ip, value.network.prefixlen))
170+
return str(value)
171+
162172
def form_class(self):
163173
if self.store_prefix_length:
164174
return InetAddressFormField

test/tests/test_sql_fields.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,12 @@ def test_host(self):
432432
instance = self.model.objects.get(field__host='10.1.2.3/27')
433433
self.assertEqual(str(instance.field), '10.1.2.3/24')
434434

435+
@skipIf(PYTHON_VERSION < (3, 9), 'Scopes were added in Python 3.9')
436+
def test_ipv6_strip_scope(self):
437+
instance = self.model.objects.create(field='2001:db8::1%foo/64')
438+
instance = self.model.objects.get(pk=instance.pk)
439+
self.assertEqual(str(instance.field), '2001:db8::1/64')
440+
435441

436442
class TestInetFieldNullable(BaseInetFieldTestCase, TestCase):
437443
def setUp(self):

0 commit comments

Comments
 (0)