-
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 move IPAddressField to field_serializers
- Loading branch information
Showing
3 changed files
with
40 additions
and
32 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,38 @@ | ||
from django.utils.translation import gettext_lazy as _ | ||
from rest_framework import serializers | ||
|
||
from ipam import models | ||
from ipam.validators import validate_ipaddress_with_mask | ||
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 __init__(self, **kwargs): | ||
super().__init__(**kwargs) | ||
validator = validate_ipaddress_with_mask | ||
self.validators.append(validator) | ||
|
||
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