PageRenderTime 96ms CodeModel.GetById 44ms app.highlight 10ms RepoModel.GetById 30ms app.codeStats 0ms

/django/contrib/localflavor/de/forms.py

https://code.google.com/p/mango-py/
Python | 84 lines | 61 code | 6 blank | 17 comment | 0 complexity | ec187b2cb38dabab4b8a85de31e89f86 MD5 | raw file
 1"""
 2DE-specific Form helpers
 3"""
 4
 5from django.core.validators import EMPTY_VALUES
 6from django.forms import ValidationError
 7from django.forms.fields import Field, RegexField, Select
 8from django.utils.translation import ugettext_lazy as _
 9import re
10
11id_re = re.compile(r"^(?P<residence>\d{10})(?P<origin>\w{1,3})[-\ ]?(?P<birthday>\d{7})[-\ ]?(?P<validity>\d{7})[-\ ]?(?P<checksum>\d{1})$")
12
13class DEZipCodeField(RegexField):
14    default_error_messages = {
15        'invalid': _('Enter a zip code in the format XXXXX.'),
16    }
17    def __init__(self, *args, **kwargs):
18        super(DEZipCodeField, self).__init__(r'^\d{5}$',
19            max_length=None, min_length=None, *args, **kwargs)
20
21class DEStateSelect(Select):
22    """
23    A Select widget that uses a list of DE states as its choices.
24    """
25    def __init__(self, attrs=None):
26        from de_states import STATE_CHOICES
27        super(DEStateSelect, self).__init__(attrs, choices=STATE_CHOICES)
28
29class DEIdentityCardNumberField(Field):
30    """
31    A German identity card number.
32
33    Checks the following rules to determine whether the number is valid:
34
35        * Conforms to the XXXXXXXXXXX-XXXXXXX-XXXXXXX-X format.
36        * No group consists entirely of zeroes.
37        * Included checksums match calculated checksums
38
39    Algorithm is documented at http://de.wikipedia.org/wiki/Personalausweis
40    """
41    default_error_messages = {
42        'invalid': _('Enter a valid German identity card number in XXXXXXXXXXX-XXXXXXX-XXXXXXX-X format.'),
43    }
44
45    def has_valid_checksum(self, number):
46        given_number, given_checksum = number[:-1], number[-1]
47        calculated_checksum = 0
48        fragment = ""
49        parameter = 7
50
51        for i in range(len(given_number)):
52            fragment = str(int(given_number[i]) * parameter)
53            if fragment.isalnum():
54                calculated_checksum += int(fragment[-1])
55            if parameter == 1:
56                parameter = 7
57            elif parameter == 3:
58                parameter = 1
59            elif parameter ==7:
60                parameter = 3
61
62        return str(calculated_checksum)[-1] == given_checksum
63
64    def clean(self, value):
65        super(DEIdentityCardNumberField, self).clean(value)
66        if value in EMPTY_VALUES:
67            return u''
68        match = re.match(id_re, value)
69        if not match:
70            raise ValidationError(self.error_messages['invalid'])
71
72        gd = match.groupdict()
73        residence, origin = gd['residence'], gd['origin']
74        birthday, validity, checksum = gd['birthday'], gd['validity'], gd['checksum']
75
76        if residence == '0000000000' or birthday == '0000000' or validity == '0000000':
77            raise ValidationError(self.error_messages['invalid'])
78
79        all_digits = u"%s%s%s%s" % (residence, birthday, validity, checksum)
80        if not self.has_valid_checksum(residence) or not self.has_valid_checksum(birthday) or \
81            not self.has_valid_checksum(validity) or not self.has_valid_checksum(all_digits):
82                raise ValidationError(self.error_messages['invalid'])
83
84        return u'%s%s-%s-%s-%s' % (residence, origin, birthday, validity, checksum)