2 Iceland specific form helpers.
5 from django
.core
.validators
import EMPTY_VALUES
6 from django
.forms
import ValidationError
7 from django
.forms
.fields
import RegexField
8 from django
.forms
.widgets
import Select
9 from django
.utils
.translation
import ugettext_lazy
as _
10 from django
.utils
.encoding
import smart_unicode
12 class ISIdNumberField(RegexField
):
14 Icelandic identification number (kennitala). This is a number every citizen
17 default_error_messages
= {
18 'invalid': _('Enter a valid Icelandic identification number. The format is XXXXXX-XXXX.'),
19 'checksum': _(u
'The Icelandic identification number is not valid.'),
22 def __init__(self
, *args
, **kwargs
):
23 kwargs
['min_length'],kwargs
['max_length'] = 10,11
24 super(ISIdNumberField
, self
).__init
__(r
'^\d{6}(-| )?\d{4}$', *args
, **kwargs
)
26 def clean(self
, value
):
27 value
= super(ISIdNumberField
, self
).clean(value
)
29 if value
in EMPTY_VALUES
:
32 value
= self
._canonify
(value
)
33 if self
._validate
(value
):
34 return self
._format
(value
)
36 raise ValidationError(self
.error_messages
['checksum'])
38 def _canonify(self
, value
):
40 Returns the value as only digits.
42 return value
.replace('-', '').replace(' ', '')
44 def _validate(self
, value
):
46 Takes in the value in canonical form and checks the verifier digit. The
49 check
= [3, 2, 7, 6, 5, 4, 3, 2, 1, 0]
50 return sum([int(value
[i
]) * check
[i
] for i
in range(10)]) % 11 == 0
52 def _format(self
, value
):
54 Takes in the value in canonical form and returns it in the common
57 return smart_unicode(value
[:6]+'-'+value
[6:])
59 class ISPhoneNumberField(RegexField
):
61 Icelandic phone number. Seven digits with an optional hyphen or space after
62 the first three digits.
64 def __init__(self
, *args
, **kwargs
):
65 kwargs
['min_length'], kwargs
['max_length'] = 7,8
66 super(ISPhoneNumberField
, self
).__init
__(r
'^\d{3}(-| )?\d{4}$', *args
, **kwargs
)
68 def clean(self
, value
):
69 value
= super(ISPhoneNumberField
, self
).clean(value
)
71 if value
in EMPTY_VALUES
:
74 return value
.replace('-', '').replace(' ', '')
76 class ISPostalCodeSelect(Select
):
78 A Select widget that uses a list of Icelandic postal codes as its choices.
80 def __init__(self
, attrs
=None):
81 from is_postalcodes
import IS_POSTALCODES
82 super(ISPostalCodeSelect
, self
).__init
__(attrs
, choices
=IS_POSTALCODES
)