PageRenderTime 21ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/localflavor/uk/forms.py

https://code.google.com/p/mango-py/
Python | 53 lines | 38 code | 4 blank | 11 comment | 1 complexity | 257be323333345071b1599210c2d57fd MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. UK-specific Form helpers
  3. """
  4. import re
  5. from django.forms.fields import CharField, Select
  6. from django.forms import ValidationError
  7. from django.utils.translation import ugettext_lazy as _
  8. class UKPostcodeField(CharField):
  9. """
  10. A form field that validates its input is a UK postcode.
  11. The regular expression used is sourced from the schema for British Standard
  12. BS7666 address types: http://www.govtalk.gov.uk/gdsc/schemas/bs7666-v2-0.xsd
  13. The value is uppercased and a space added in the correct place, if required.
  14. """
  15. default_error_messages = {
  16. 'invalid': _(u'Enter a valid postcode.'),
  17. }
  18. outcode_pattern = '[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW])'
  19. incode_pattern = '[0-9][ABD-HJLNP-UW-Z]{2}'
  20. postcode_regex = re.compile(r'^(GIR 0AA|%s %s)$' % (outcode_pattern, incode_pattern))
  21. space_regex = re.compile(r' *(%s)$' % incode_pattern)
  22. def clean(self, value):
  23. value = super(UKPostcodeField, self).clean(value)
  24. if value == u'':
  25. return value
  26. postcode = value.upper().strip()
  27. # Put a single space before the incode (second part).
  28. postcode = self.space_regex.sub(r' \1', postcode)
  29. if not self.postcode_regex.search(postcode):
  30. raise ValidationError(self.error_messages['invalid'])
  31. return postcode
  32. class UKCountySelect(Select):
  33. """
  34. A Select widget that uses a list of UK Counties/Regions as its choices.
  35. """
  36. def __init__(self, attrs=None):
  37. from uk_regions import UK_REGION_CHOICES
  38. super(UKCountySelect, self).__init__(attrs, choices=UK_REGION_CHOICES)
  39. class UKNationSelect(Select):
  40. """
  41. A Select widget that uses a list of UK Nations as its choices.
  42. """
  43. def __init__(self, attrs=None):
  44. from uk_regions import UK_NATIONS_CHOICES
  45. super(UKNationSelect, self).__init__(attrs, choices=UK_NATIONS_CHOICES)