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

/django/contrib/localflavor/pl/forms.py

https://code.google.com/p/mango-py/
Python | 160 lines | 135 code | 7 blank | 18 comment | 5 complexity | a89b01f47658f349a18a3c009069a89c MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. Polish-specific form helpers
  3. """
  4. import re
  5. from django.forms import ValidationError
  6. from django.forms.fields import Select, RegexField
  7. from django.utils.translation import ugettext_lazy as _
  8. from django.core.validators import EMPTY_VALUES
  9. class PLProvinceSelect(Select):
  10. """
  11. A select widget with list of Polish administrative provinces as choices.
  12. """
  13. def __init__(self, attrs=None):
  14. from pl_voivodeships import VOIVODESHIP_CHOICES
  15. super(PLProvinceSelect, self).__init__(attrs, choices=VOIVODESHIP_CHOICES)
  16. class PLCountySelect(Select):
  17. """
  18. A select widget with list of Polish administrative units as choices.
  19. """
  20. def __init__(self, attrs=None):
  21. from pl_administrativeunits import ADMINISTRATIVE_UNIT_CHOICES
  22. super(PLCountySelect, self).__init__(attrs, choices=ADMINISTRATIVE_UNIT_CHOICES)
  23. class PLPESELField(RegexField):
  24. """
  25. A form field that validates as Polish Identification Number (PESEL).
  26. Checks the following rules:
  27. * the length consist of 11 digits
  28. * has a valid checksum
  29. The algorithm is documented at http://en.wikipedia.org/wiki/PESEL.
  30. """
  31. default_error_messages = {
  32. 'invalid': _(u'National Identification Number consists of 11 digits.'),
  33. 'checksum': _(u'Wrong checksum for the National Identification Number.'),
  34. }
  35. def __init__(self, *args, **kwargs):
  36. super(PLPESELField, self).__init__(r'^\d{11}$',
  37. max_length=None, min_length=None, *args, **kwargs)
  38. def clean(self,value):
  39. super(PLPESELField, self).clean(value)
  40. if value in EMPTY_VALUES:
  41. return u''
  42. if not self.has_valid_checksum(value):
  43. raise ValidationError(self.error_messages['checksum'])
  44. return u'%s' % value
  45. def has_valid_checksum(self, number):
  46. """
  47. Calculates a checksum with the provided algorithm.
  48. """
  49. multiple_table = (1, 3, 7, 9, 1, 3, 7, 9, 1, 3, 1)
  50. result = 0
  51. for i in range(len(number)):
  52. result += int(number[i]) * multiple_table[i]
  53. return result % 10 == 0
  54. class PLNIPField(RegexField):
  55. """
  56. A form field that validates as Polish Tax Number (NIP).
  57. Valid forms are: XXX-XXX-YY-YY or XX-XX-YYY-YYY.
  58. Checksum algorithm based on documentation at
  59. http://wipos.p.lodz.pl/zylla/ut/nip-rego.html
  60. """
  61. default_error_messages = {
  62. 'invalid': _(u'Enter a tax number field (NIP) in the format XXX-XXX-XX-XX or XX-XX-XXX-XXX.'),
  63. 'checksum': _(u'Wrong checksum for the Tax Number (NIP).'),
  64. }
  65. def __init__(self, *args, **kwargs):
  66. super(PLNIPField, self).__init__(r'^\d{3}-\d{3}-\d{2}-\d{2}$|^\d{2}-\d{2}-\d{3}-\d{3}$',
  67. max_length=None, min_length=None, *args, **kwargs)
  68. def clean(self,value):
  69. super(PLNIPField, self).clean(value)
  70. if value in EMPTY_VALUES:
  71. return u''
  72. value = re.sub("[-]", "", value)
  73. if not self.has_valid_checksum(value):
  74. raise ValidationError(self.error_messages['checksum'])
  75. return u'%s' % value
  76. def has_valid_checksum(self, number):
  77. """
  78. Calculates a checksum with the provided algorithm.
  79. """
  80. multiple_table = (6, 5, 7, 2, 3, 4, 5, 6, 7)
  81. result = 0
  82. for i in range(len(number)-1):
  83. result += int(number[i]) * multiple_table[i]
  84. result %= 11
  85. if result == int(number[-1]):
  86. return True
  87. else:
  88. return False
  89. class PLREGONField(RegexField):
  90. """
  91. A form field that validates its input is a REGON number.
  92. Valid regon number consists of 9 or 14 digits.
  93. See http://www.stat.gov.pl/bip/regon_ENG_HTML.htm for more information.
  94. """
  95. default_error_messages = {
  96. 'invalid': _(u'National Business Register Number (REGON) consists of 9 or 14 digits.'),
  97. 'checksum': _(u'Wrong checksum for the National Business Register Number (REGON).'),
  98. }
  99. def __init__(self, *args, **kwargs):
  100. super(PLREGONField, self).__init__(r'^\d{9,14}$',
  101. max_length=None, min_length=None, *args, **kwargs)
  102. def clean(self,value):
  103. super(PLREGONField, self).clean(value)
  104. if value in EMPTY_VALUES:
  105. return u''
  106. if not self.has_valid_checksum(value):
  107. raise ValidationError(self.error_messages['checksum'])
  108. return u'%s' % value
  109. def has_valid_checksum(self, number):
  110. """
  111. Calculates a checksum with the provided algorithm.
  112. """
  113. weights = (
  114. (8, 9, 2, 3, 4, 5, 6, 7, -1),
  115. (2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8, -1),
  116. (8, 9, 2, 3, 4, 5, 6, 7, -1, 0, 0, 0, 0, 0),
  117. )
  118. weights = [table for table in weights if len(table) == len(number)]
  119. for table in weights:
  120. checksum = sum([int(n) * w for n, w in zip(number, table)])
  121. if checksum % 11 % 10:
  122. return False
  123. return bool(weights)
  124. class PLPostalCodeField(RegexField):
  125. """
  126. A form field that validates as Polish postal code.
  127. Valid code is XX-XXX where X is digit.
  128. """
  129. default_error_messages = {
  130. 'invalid': _(u'Enter a postal code in the format XX-XXX.'),
  131. }
  132. def __init__(self, *args, **kwargs):
  133. super(PLPostalCodeField, self).__init__(r'^\d{2}-\d{3}$',
  134. max_length=None, min_length=None, *args, **kwargs)