Ticket #3988: patch.diff

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

Addition of .ca localflavor code

  • ca/ca_provinces.py

     
     1"""
     2An alphabetical list of provinces and territories for use as `choices`
     3in a formfield.
     4
     5Source: http://www.canada.gc.ca/othergov/prov_e.html
     6
     7This exists in this standalone file so that it's only imported into memory
     8when explicitly needed.
     9"""
     10
     11PROVINCE_CHOICES = (
     12    ('AB', 'Alberta'),
     13    ('BC', 'British Columbia'),
     14    ('MB', 'Manitoba'),
     15    ('NB', 'New Brunswick'),
     16    ('NF', 'Newfoundland and Labrador'),
     17    ('NT', 'Northwest Territories'),
     18    ('NS', 'Nova Scotia'),
     19    ('NU', 'Nunavut'),
     20    ('ON', 'Ontario'),
     21    ('PE', 'Prince Edward Island'),
     22    ('QC', 'Quebec'),
     23    ('SK', 'Saskatchewan'),
     24    ('YK', 'Yukon')
     25)
  • ca/forms.py

     
     1"""
     2Canada-specific Form helpers
     3"""
     4
     5from django.newforms import ValidationError
     6from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES
     7from django.newforms.util import smart_unicode
     8from django.utils.translation import gettext
     9import re
     10
     11PHONE_DIGITS_RE = re.compile(r'^(\d{10})$')
     12
     13class CAPostCodeField(RegexField):
     14    """Canadian post code field."""
     15    def __init__(self, *args, **kwargs):
     16        super(CAPostCodeField, self).__init__(r'^[A-Z]\d[A-Z] \d[A-Z]\d$',
     17            max_length=None, min_length=None,
     18            error_message=gettext(u'Enter correct postal code.'),
     19            *args, **kwargs)
     20
     21class CAPhoneNumberField(Field):
     22    """Canadian phone number field."""
     23    def clean(self, value):
     24        """Validate a phone number. Strips parentheses, whitespace and
     25        hyphens.
     26        """
     27        super(CAPhoneNumberField, self).clean(value)
     28        if value in EMPTY_VALUES:
     29            return u''
     30        value = re.sub('(\(|\)|\s+|-)', '', smart_unicode(value))
     31        phone_match = PHONE_DIGITS_RE.search(value)
     32        if phone_match:
     33            return u'%s' % phone_match.group(1)
     34        raise ValidationError(u'Phone numbers must contain 10 digits.')
     35
     36class CAProvinceSelect(Select):
     37    """
     38    A Select widget that uses a list of Canadian provinces and
     39    territories as its choices.
     40    """
     41    def __init__(self, attrs=None):
     42        from ca_provinces import PROVINCE_CHOICES # relative import
     43        super(CAStateSelect, self).__init__(attrs, choices=PROVINCE_CHOICES)
Back to Top