# CCS CS Lab Laptops Forms # # Douglas Thrift # # $Id$ from ccscslab.main.models import Person from ccscslab.laptops.models import Laptop from django import forms from django.forms.models import inlineformset_factory from django.utils.translation import ugettext_lazy as _ import re mac_address = re.compile(r'^(?:[0-9A-Fa-f]{6}[-:]?[0-9A-Fa-f]{6}|[0-9A-Fa-f]{4}(?:.[0-9A-Fa-f]{4}){2}|[0-9A-Fa-f]{2}(?:[-:][0-9A-Fa-f]{2}){5})$') mac_separator = re.compile(r'[-.:]') class MACAddressField(forms.RegexField): default_error_messages = { 'invalid': _(u'Enter a valid MAC address.'), } def __init__(self, *args, **kwargs): super(MACAddressField, self).__init__(mac_address, *args, **kwargs) def clean(self, value): value = ''.join(mac_separator.split(super(MACAddressField, self).clean(value))).lower() return ':'.join((value[begin:end] for begin, end in ((index, index + 2) for index in range(0, 12, 2)))) def widget_attrs(self, widget): if isinstance(widget, (forms.TextInput, forms.PasswordInput)): return {'maxlength': '17', 'size': '17'} class LaptopForm(forms.ModelForm): fancy_name = forms.CharField(required = False, widget = forms.TextInput(attrs = {'maxlength': 50, 'size': 50})) class Meta: model = Laptop PersonLaptopFormSet = inlineformset_factory(Person, Laptop, LaptopForm, extra = 1, fields = ('mac_address', 'fancy_name')) class MACLookupForm(forms.Form): mac_address = MACAddressField(label = 'MAC Address')