Code

Ticket #3988: patch.diff

File patch.diff, 2.6 KB (added by pi, 7 years ago)

Addition of .ca localflavor code

Line 
1Index: ca/ca_provinces.py
2===================================================================
3--- ca/ca_provinces.py  (revision 0)
4+++ ca/ca_provinces.py  (revision 0)
5@@ -0,0 +1,25 @@
6+"""
7+An alphabetical list of provinces and territories for use as `choices`
8+in a formfield.
9+
10+Source: http://www.canada.gc.ca/othergov/prov_e.html
11+
12+This exists in this standalone file so that it's only imported into memory
13+when explicitly needed.
14+"""
15+
16+PROVINCE_CHOICES = (
17+    ('AB', 'Alberta'),
18+    ('BC', 'British Columbia'),
19+    ('MB', 'Manitoba'),
20+    ('NB', 'New Brunswick'),
21+    ('NF', 'Newfoundland and Labrador'),
22+    ('NT', 'Northwest Territories'),
23+    ('NS', 'Nova Scotia'),
24+    ('NU', 'Nunavut'),
25+    ('ON', 'Ontario'),
26+    ('PE', 'Prince Edward Island'),
27+    ('QC', 'Quebec'),
28+    ('SK', 'Saskatchewan'),
29+    ('YK', 'Yukon')
30+)
31Index: ca/__init__.py
32===================================================================
33Index: ca/forms.py
34===================================================================
35--- ca/forms.py (revision 0)
36+++ ca/forms.py (revision 0)
37@@ -0,0 +1,43 @@
38+"""
39+Canada-specific Form helpers
40+"""
41+
42+from django.newforms import ValidationError
43+from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES
44+from django.newforms.util import smart_unicode
45+from django.utils.translation import gettext
46+import re
47+
48+PHONE_DIGITS_RE = re.compile(r'^(\d{10})$')
49+
50+class CAPostCodeField(RegexField):
51+    """Canadian post code field."""
52+    def __init__(self, *args, **kwargs):
53+        super(CAPostCodeField, self).__init__(r'^[A-Z]\d[A-Z] \d[A-Z]\d$',
54+            max_length=None, min_length=None,
55+            error_message=gettext(u'Enter correct postal code.'),
56+            *args, **kwargs)
57+
58+class CAPhoneNumberField(Field):
59+    """Canadian phone number field."""
60+    def clean(self, value):
61+        """Validate a phone number. Strips parentheses, whitespace and
62+        hyphens.
63+        """
64+        super(CAPhoneNumberField, self).clean(value)
65+        if value in EMPTY_VALUES:
66+            return u''
67+        value = re.sub('(\(|\)|\s+|-)', '', smart_unicode(value))
68+        phone_match = PHONE_DIGITS_RE.search(value)
69+        if phone_match:
70+            return u'%s' % phone_match.group(1)
71+        raise ValidationError(u'Phone numbers must contain 10 digits.')
72+
73+class CAProvinceSelect(Select):
74+    """
75+    A Select widget that uses a list of Canadian provinces and
76+    territories as its choices.
77+    """
78+    def __init__(self, attrs=None):
79+        from ca_provinces import PROVINCE_CHOICES # relative import
80+        super(CAStateSelect, self).__init__(attrs, choices=PROVINCE_CHOICES)