fields.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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 = {
  11. 'invalid': _(u'Enter a valid MAC address.'),
  12. }
  13. def __init__(self, *args, **kwargs):
  14. super(MACAddressFormField, self).__init__(mac_re, *args, **kwargs)
  15. class MACAddressField(models.Field):
  16. empty_strings_allowed = False
  17. def __init__(self, *args, **kwargs):
  18. kwargs['max_length'] = 17
  19. super(MACAddressField, self).__init__(*args, **kwargs)
  20. def get_internal_type(self):
  21. return "CharField"
  22. def formfield(self, **kwargs):
  23. defaults = {'form_class': MACAddressFormField}
  24. defaults.update(kwargs)
  25. return super(MACAddressField, self).formfield(**defaults)
  26. # def get_db_prep_value(self, value, *args, **kwargs):
  27. # return filter(lambda ch: ch not in ':-', value).upper()