fields.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import re
  4. from django.utils.translation import ugettext_lazy as _
  5. from django.forms import fields
  6. from django.db import models
  7. MAC_RE = r"^([0-9a-fA-F]{2}([:-]?|$)){6}$"
  8. mac_re = re.compile(MAC_RE)
  9. class MACAddressFormField(fields.RegexField):
  10. default_error_messages = {"invalid": _("Enter a valid MAC address.")}
  11. def __init__(self, *args, **kwargs):
  12. super(MACAddressFormField, self).__init__(mac_re, *args, **kwargs)
  13. class MACAddressField(models.Field):
  14. empty_strings_allowed = False
  15. def __init__(self, *args, **kwargs):
  16. kwargs["max_length"] = 17
  17. super(MACAddressField, self).__init__(*args, **kwargs)
  18. def get_internal_type(self):
  19. return "CharField"
  20. def formfield(self, **kwargs):
  21. defaults = {"form_class": MACAddressFormField}
  22. defaults.update(kwargs)
  23. return super(MACAddressField, self).formfield(**defaults)
  24. # def get_db_prep_value(self, value, *args, **kwargs):
  25. # return filter(lambda ch: ch not in ':-', value).upper()