Add Django-1.2.1
[frozenviper.git] / Django-1.2.1 / django / contrib / localflavor / is_ / forms.py
blobabf858df2bc10798773b61da3471614d09037d8e
1 """
2 Iceland specific form helpers.
3 """
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):
13 """
14 Icelandic identification number (kennitala). This is a number every citizen
15 of Iceland has.
16 """
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:
30 return u''
32 value = self._canonify(value)
33 if self._validate(value):
34 return self._format(value)
35 else:
36 raise ValidationError(self.error_messages['checksum'])
38 def _canonify(self, value):
39 """
40 Returns the value as only digits.
41 """
42 return value.replace('-', '').replace(' ', '')
44 def _validate(self, value):
45 """
46 Takes in the value in canonical form and checks the verifier digit. The
47 method is modulo 11.
48 """
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):
53 """
54 Takes in the value in canonical form and returns it in the common
55 display format.
56 """
57 return smart_unicode(value[:6]+'-'+value[6:])
59 class ISPhoneNumberField(RegexField):
60 """
61 Icelandic phone number. Seven digits with an optional hyphen or space after
62 the first three digits.
63 """
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:
72 return u''
74 return value.replace('-', '').replace(' ', '')
76 class ISPostalCodeSelect(Select):
77 """
78 A Select widget that uses a list of Icelandic postal codes as its choices.
79 """
80 def __init__(self, attrs=None):
81 from is_postalcodes import IS_POSTALCODES
82 super(ISPostalCodeSelect, self).__init__(attrs, choices=IS_POSTALCODES)