Login

BRPhoneNumberWidget

Author:
semente
Posted:
August 28, 2011
Language:
Python
Version:
1.3
Tags:
phone br localflavor BRPhoneNumberField
Score:
0 (after 0 ratings)

A widget created for BRPhoneNumberField that splits the input into a <input> for the area code and another for the phone number.

Usage example:

class MyForm(forms.Form):

    mobile_phone = BRPhoneNumberField(
        label='Telefone Celular',
        widget=BRPhoneNumberWidget()
    )

  ...
 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
    <input> 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)

More like this

  1. Phone Model by harobed 6 years, 7 months ago
  2. Bootstrap button dropdown widget (replaces forms.Select) by benjaoming 2 years, 12 months ago
  3. Radio widget with labels after inputs by avsd 3 years ago
  4. Honeypot Field by SmileyChris 8 years, 4 months ago
  5. boostrap prepend-input for widgets by DimmuR 2 years, 10 months ago

Comments

Please login first before commenting.