PageRenderTime 122ms CodeModel.GetById 50ms app.highlight 7ms RepoModel.GetById 64ms app.codeStats 0ms

/django/contrib/localflavor/is_/forms.py

https://code.google.com/p/mango-py/
Python | 83 lines | 71 code | 5 blank | 7 comment | 2 complexity | 825880eb97ee8d264d9317040c97fff5 MD5 | raw file
 1"""
 2Iceland specific form helpers.
 3"""
 4
 5from django.core.validators import EMPTY_VALUES
 6from django.forms import ValidationError
 7from django.forms.fields import RegexField
 8from django.forms.widgets import Select
 9from django.utils.translation import ugettext_lazy as _
10from django.utils.encoding import smart_unicode
11
12class 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.'),
20    }
21
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)
25
26    def clean(self, value):
27        value = super(ISIdNumberField, self).clean(value)
28
29        if value in EMPTY_VALUES:
30            return u''
31
32        value = self._canonify(value)
33        if self._validate(value):
34            return self._format(value)
35        else:
36            raise ValidationError(self.error_messages['checksum'])
37
38    def _canonify(self, value):
39        """
40        Returns the value as only digits.
41        """
42        return value.replace('-', '').replace(' ', '')
43
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
51
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:])
58
59class 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)
67
68    def clean(self, value):
69        value = super(ISPhoneNumberField, self).clean(value)
70
71        if value in EMPTY_VALUES:
72            return u''
73
74        return value.replace('-', '').replace(' ', '')
75
76class 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)
83