from django.contrib.localflavor.br.forms import phone_digits_re from django.forms import widgets from django.utils.safestring import mark_safe class BRPhoneNumberWidget(widgets.Widget): """ A widget created for BRPhoneNumberField that splits the input into a for the area code and another for the phone number. """ area_code_field = '%s_area_code' number_field = '%s_number' def __init__(self, attrs=None, required=True): self.attrs = attrs or {} self.required = required def create_input(self, name, field, val): if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name local_attrs = self.build_attrs(id=field % id_) input_ = widgets.TextInput() input_html = input_.render(field % name, val, local_attrs) return input_html def render(self, name, value, attrs=None): area_code = number = None try: match = phone_digits_re.match(value) if match: area_code, number1, number2 = [v for v in match.groups()] number = u'%s-%s' % (number1, number2) except TypeError: pass area_code_html = self.create_input(name, self.area_code_field, area_code) number_html = self.create_input(name, self.number_field, number) output = u'%s\n%s' % (area_code_html, number_html) return mark_safe(output) def value_from_datadict(self, data, files, name): area_code = data.get(self.area_code_field % name) number = data.get(self.number_field % name) if area_code and number: return '%s-%s' % (area_code, number) return data.get(name, None)