fields.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from __future__ import unicode_literals
  2. from netaddr import EUI, mac_unix_expanded
  3. from django.core.exceptions import ValidationError
  4. from django.core.validators import MinValueValidator, MaxValueValidator
  5. from django.db import models
  6. from .formfields import MACAddressFormField
  7. class ASNField(models.BigIntegerField):
  8. description = "32-bit ASN field"
  9. default_validators = [
  10. MinValueValidator(1),
  11. MaxValueValidator(4294967295),
  12. ]
  13. class mac_unix_expanded_uppercase(mac_unix_expanded):
  14. word_fmt = '%.2X'
  15. class MACAddressField(models.Field):
  16. description = "PostgreSQL MAC Address field"
  17. def python_type(self):
  18. return EUI
  19. def from_db_value(self, value, expression, connection, context):
  20. return self.to_python(value)
  21. def to_python(self, value):
  22. if value is None:
  23. return value
  24. try:
  25. return EUI(value, version=48, dialect=mac_unix_expanded_uppercase)
  26. except ValueError as e:
  27. raise ValidationError(e)
  28. def db_type(self, connection):
  29. return 'macaddr'
  30. def get_prep_value(self, value):
  31. if not value:
  32. return None
  33. return str(self.to_python(value))
  34. def form_class(self):
  35. return MACAddressFormField
  36. def formfield(self, **kwargs):
  37. defaults = {'form_class': self.form_class()}
  38. defaults.update(kwargs)
  39. return super(MACAddressField, self).formfield(**defaults)