Login

MAC address field

Author:
diverman
Posted:
February 23, 2009
Language:
Python
Version:
1.0
Tags:
model field custom-field address mac
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. Unzip a .zip file uploaded with FileBrowser by shacker 5 years, 6 months ago
  2. Address model by harobed 6 years, 8 months ago
  3. Google map on admin address field by coulix 4 years, 11 months ago
  4. Multiple emails form field by virhilo 5 years, 4 months ago
  5. Tuned IPAddressField with IPv4 & IPv6 support by diverman 6 years, 4 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.