-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
12278 add ipaddressfield serializer for OpenAPI spectacular typing (#…
…12285) * #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
- Loading branch information
Showing
3 changed files
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters