forms.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. """
  2. Australian-specific Form helpers
  3. """
  4. from __future__ import absolute_import, unicode_literals
  5. import re
  6. from django.contrib.localflavor.au.au_states import STATE_CHOICES
  7. from django.core.validators import EMPTY_VALUES
  8. from django.forms import ValidationError
  9. from django.forms.fields import Field, RegexField, Select
  10. from django.utils.encoding import smart_text
  11. from django.utils.translation import ugettext_lazy as _
  12. PHONE_DIGITS_RE = re.compile(r'^(\d{10})$')
  13. class AUPostCodeField(RegexField):
  14. """ Australian post code field.
  15. Assumed to be 4 digits.
  16. Northern Territory 3-digit postcodes should have leading zero.
  17. """
  18. default_error_messages = {
  19. 'invalid': _('Enter a 4 digit postcode.'),
  20. }
  21. def __init__(self, max_length=4, min_length=None, *args, **kwargs):
  22. super(AUPostCodeField, self).__init__(r'^\d{4}$',
  23. max_length, min_length, *args, **kwargs)
  24. class AUPhoneNumberField(Field):
  25. """Australian phone number field."""
  26. default_error_messages = {
  27. 'invalid': 'Phone numbers must contain 10 digits.',
  28. }
  29. def clean(self, value):
  30. """
  31. Validate a phone number. Strips parentheses, whitespace and hyphens.
  32. """
  33. super(AUPhoneNumberField, self).clean(value)
  34. if value in EMPTY_VALUES:
  35. return ''
  36. value = re.sub('(\(|\)|\s+|-)', '', smart_text(value))
  37. phone_match = PHONE_DIGITS_RE.search(value)
  38. if phone_match:
  39. return '%s' % phone_match.group(1)
  40. raise ValidationError(self.error_messages['invalid'])
  41. class AUStateSelect(Select):
  42. """
  43. A Select widget that uses a list of Australian states/territories as its
  44. choices.
  45. """
  46. def __init__(self, attrs=None):
  47. super(AUStateSelect, self).__init__(attrs, choices=STATE_CHOICES)