Skip to content

Commit

Permalink
#12278 add serializer for ipaddressfield to remove spectacular warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
arthanson committed Apr 18, 2023
1 parent 4452f57 commit 91e546c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
16 changes: 16 additions & 0 deletions netbox/ipam/api/serializers.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import gettext_lazy as _
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers

from dcim.api.nested_serializers import NestedDeviceSerializer, NestedSiteSerializer
from ipam.choices import *
from ipam.constants import IPADDRESS_ASSIGNMENT_MODELS, VLANGROUP_SCOPE_TYPES
from ipam.models import *
from ipam.validators import validate_ipaddress_with_mask
from netaddr import AddrFormatError, IPNetwork
from netbox.api.fields import ChoiceField, ContentTypeField, SerializedPKRelatedField
from netbox.api.serializers import NetBoxModelSerializer
from netbox.constants import NESTED_SERIALIZER_PREFIX
Expand Down Expand Up @@ -387,10 +390,23 @@ class Meta:
#
# IP addresses
#
class IPAddressField(serializers.CharField):
"""IPAddressField with mask"""

default_error_messages = {
'invalid': _('Enter a valid IPv4 or IPv6 address with optional mask.'),
}

def __init__(self, **kwargs):
super().__init__(**kwargs)
validator = validate_ipaddress_with_mask
self.validators.append(validator)


class IPAddressSerializer(NetBoxModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='ipam-api:ipaddress-detail')
family = ChoiceField(choices=IPAddressFamilyChoices, read_only=True)
address = IPAddressField()
vrf = NestedVRFSerializer(required=False, allow_null=True)
tenant = NestedTenantSerializer(required=False, allow_null=True)
status = ChoiceField(choices=IPAddressStatusChoices, required=False)
Expand Down
11 changes: 11 additions & 0 deletions netbox/ipam/validators.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.core.exceptions import ValidationError
from django.core.validators import BaseValidator, RegexValidator
from netaddr import AddrFormatError, IPNetwork


def prefix_validator(prefix):
Expand Down Expand Up @@ -28,3 +29,13 @@ def compare(self, a, b):
message='Only alphanumeric characters, asterisks, hyphens, periods, and underscores are allowed in DNS names',
code='invalid'
)


def validate_ipaddress_with_mask(address):
if address:
try:
IPNetwork(address)
except AddrFormatError:
raise ValidationError("Invalid IP address format: {}".format(address))
except (TypeError, ValueError) as e:
raise ValidationError(e)

0 comments on commit 91e546c

Please sign in to comment.