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