mirror of
https://github.com/netbox-community/netbox.git
synced 2024-05-10 07:54:54 +00:00
* #12278 add serializer for ipaddressfield to remove spectacular warnings * #12278 add ipaddressfieldserializer to nested serializers * #12278 fix to_internal_value to_representation in serializer * #12278 to_internal_value is called before validation! need to raise validation error if incorrect format * #12278 to_internal_value needs to return value doh * #12278 move IPAddressField to field_serializers * #12278 remove old import * 12278 remove validator
33 lines
800 B
Python
33 lines
800 B
Python
from django.utils.translation import gettext_lazy as _
|
|
from rest_framework import serializers
|
|
|
|
from ipam import models
|
|
from netaddr import AddrFormatError, IPNetwork
|
|
|
|
__all__ = [
|
|
'IPAddressField',
|
|
]
|
|
|
|
|
|
#
|
|
# IP address field
|
|
#
|
|
|
|
class IPAddressField(serializers.CharField):
|
|
"""IPAddressField with mask"""
|
|
|
|
default_error_messages = {
|
|
'invalid': _('Enter a valid IPv4 or IPv6 address with optional mask.'),
|
|
}
|
|
|
|
def to_internal_value(self, data):
|
|
try:
|
|
return IPNetwork(data)
|
|
except AddrFormatError:
|
|
raise serializers.ValidationError("Invalid IP address format: {}".format(data))
|
|
except (TypeError, ValueError) as e:
|
|
raise serializers.ValidationError(e)
|
|
|
|
def to_representation(self, value):
|
|
return str(value)
|