formfields.py 606 B

123456789101112131415161718192021222324252627
  1. from __future__ import unicode_literals
  2. from django import forms
  3. from django.core.exceptions import ValidationError
  4. from netaddr import EUI, AddrFormatError
  5. #
  6. # Form fields
  7. #
  8. class MACAddressFormField(forms.Field):
  9. default_error_messages = {
  10. 'invalid': "Enter a valid MAC address.",
  11. }
  12. def to_python(self, value):
  13. if not value:
  14. return None
  15. if isinstance(value, EUI):
  16. return value
  17. try:
  18. return EUI(value, version=48)
  19. except AddrFormatError:
  20. raise ValidationError("Please specify a valid MAC address.")