PageRenderTime 21ms CodeModel.GetById 11ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/localflavor/au/forms.py

https://code.google.com/p/mango-py/
Python | 50 lines | 36 code | 6 blank | 8 comment | 2 complexity | e902bf5e49af557b33eb4c74ac404110 MD5 | raw file
 1"""
 2Australian-specific Form helpers
 3"""
 4
 5from django.core.validators import EMPTY_VALUES
 6from django.forms import ValidationError
 7from django.forms.fields import Field, RegexField, Select
 8from django.utils.encoding import smart_unicode
 9from django.utils.translation import ugettext_lazy as _
10import re
11
12PHONE_DIGITS_RE = re.compile(r'^(\d{10})$')
13
14class AUPostCodeField(RegexField):
15    """Australian post code field."""
16    default_error_messages = {
17        'invalid': _('Enter a 4 digit post code.'),
18    }
19
20    def __init__(self, *args, **kwargs):
21        super(AUPostCodeField, self).__init__(r'^\d{4}$',
22            max_length=None, min_length=None, *args, **kwargs)
23
24class AUPhoneNumberField(Field):
25    """Australian phone number field."""
26    default_error_messages = {
27        'invalid': u'Phone numbers must contain 10 digits.',
28    }
29
30    def clean(self, value):
31        """
32        Validate a phone number. Strips parentheses, whitespace and hyphens.
33        """
34        super(AUPhoneNumberField, self).clean(value)
35        if value in EMPTY_VALUES:
36            return u''
37        value = re.sub('(\(|\)|\s+|-)', '', smart_unicode(value))
38        phone_match = PHONE_DIGITS_RE.search(value)
39        if phone_match:
40            return u'%s' % phone_match.group(1)
41        raise ValidationError(self.error_messages['invalid'])
42
43class AUStateSelect(Select):
44    """
45    A Select widget that uses a list of Australian states/territories as its
46    choices.
47    """
48    def __init__(self, attrs=None):
49        from au_states import STATE_CHOICES
50        super(AUStateSelect, self).__init__(attrs, choices=STATE_CHOICES)