2016-07-05 10:41:38 -04:00
|
|
|
from django.core.exceptions import ValidationError
|
2016-07-13 15:30:15 -04:00
|
|
|
from django.core.validators import MinValueValidator, MaxValueValidator
|
2016-07-05 10:41:38 -04:00
|
|
|
from django.db import models
|
2018-10-03 11:23:21 -04:00
|
|
|
from netaddr import AddrFormatError, EUI, mac_unix_expanded
|
2016-07-05 10:41:38 -04:00
|
|
|
|
2020-01-15 14:53:46 -05:00
|
|
|
from ipam.constants import BGP_ASN_MAX, BGP_ASN_MIN
|
2020-01-09 21:58:38 +00:00
|
|
|
|
2016-07-05 10:48:36 -04:00
|
|
|
|
2016-07-13 15:30:15 -04:00
|
|
|
class ASNField(models.BigIntegerField):
|
|
|
|
description = "32-bit ASN field"
|
|
|
|
default_validators = [
|
2020-01-09 21:58:38 +00:00
|
|
|
MinValueValidator(BGP_ASN_MIN),
|
|
|
|
MaxValueValidator(BGP_ASN_MAX),
|
2016-07-13 15:30:15 -04:00
|
|
|
]
|
|
|
|
|
2020-01-09 21:12:35 +00:00
|
|
|
def formfield(self, **kwargs):
|
2020-01-15 14:53:46 -05:00
|
|
|
defaults = {
|
|
|
|
'min_value': BGP_ASN_MIN,
|
|
|
|
'max_value': BGP_ASN_MAX,
|
|
|
|
}
|
2020-01-09 21:12:35 +00:00
|
|
|
defaults.update(**kwargs)
|
|
|
|
return super().formfield(**defaults)
|
|
|
|
|
2016-07-13 15:30:15 -04:00
|
|
|
|
2016-07-05 10:41:38 -04:00
|
|
|
class mac_unix_expanded_uppercase(mac_unix_expanded):
|
|
|
|
word_fmt = '%.2X'
|
|
|
|
|
2016-07-05 10:58:28 -04:00
|
|
|
|
2016-07-05 10:41:38 -04:00
|
|
|
class MACAddressField(models.Field):
|
|
|
|
description = "PostgreSQL MAC Address field"
|
|
|
|
|
|
|
|
def python_type(self):
|
|
|
|
return EUI
|
|
|
|
|
2019-12-09 12:32:35 -05:00
|
|
|
def from_db_value(self, value, expression, connection):
|
2016-07-05 10:41:38 -04:00
|
|
|
return self.to_python(value)
|
|
|
|
|
|
|
|
def to_python(self, value):
|
2016-07-06 14:22:34 -04:00
|
|
|
if value is None:
|
2016-07-05 10:41:38 -04:00
|
|
|
return value
|
|
|
|
try:
|
2016-07-06 14:22:34 -04:00
|
|
|
return EUI(value, version=48, dialect=mac_unix_expanded_uppercase)
|
2018-09-18 12:02:59 -04:00
|
|
|
except AddrFormatError as e:
|
2019-04-05 09:36:56 -05:00
|
|
|
raise ValidationError("Invalid MAC address format: {}".format(value))
|
2016-07-05 10:41:38 -04:00
|
|
|
|
|
|
|
def db_type(self, connection):
|
|
|
|
return 'macaddr'
|
|
|
|
|
|
|
|
def get_prep_value(self, value):
|
|
|
|
if not value:
|
|
|
|
return None
|
|
|
|
return str(self.to_python(value))
|