Login

BRPhoneNumberWidget

Author:
semente
Posted:
August 28, 2011
Language:
Python
Version:
1.3
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.