Login

MAC address field

Author:
diverman
Posted:
February 23, 2009
Language:
Python
Version:
1.0
Score:
3 (after 3 ratings)

Supported MAC formats:

aa:bb:cc:dd:ee:ff, separator : or -

aabbccddeeff

both lower case and upper case

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import re

from django.utils.translation import ugettext_lazy as _
from django.forms import fields
from django.db import models

MAC_RE = r'^([0-9a-fA-F]{2}([:-]?|$)){6}$'
mac_re = re.compile(MAC_RE)

class MACAddressFormField(fields.RegexField):
    default_error_messages = {
        'invalid': _(u'Enter a valid MAC address.'),
    }

    def __init__(self, *args, **kwargs):
        super(MACAddressFormField, self).__init__(mac_re, *args, **kwargs)

class MACAddressField(models.Field):
    empty_strings_allowed = False
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 17
        super(MACAddressField, self).__init__(*args, **kwargs)

    def get_internal_type(self):
        return "CharField"

    def formfield(self, **kwargs):
        defaults = {'form_class': MACAddressFormField}
        defaults.update(kwargs)
        return super(MACAddressField, self).formfield(**defaults)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

diverman (on February 24, 2009):

Add a method for saving in normalized format:

def get_db_prep_value(self, value):
  return filter(lambda ch: ch not in ':-', value).upper()

#

chil (on September 18, 2012):

many thanks for this snippet! actually using django 1.4.1 when saving mac address, this error occurs:

get_db_prep_value() got an unexpected keyword argument 'connection'

i fixed it this way:

def get_db_prep_value(self, value, *args, **kwargs): 
    return filter(lambda ch: ch not in ':-', value).upper()

#

Please login first before commenting.