PageRenderTime 8ms CodeModel.GetById 1ms app.highlight 5ms RepoModel.GetById 0ms app.codeStats 1ms

/django/contrib/localflavor/it/forms.py

https://code.google.com/p/mango-py/
Python | 84 lines | 67 code | 5 blank | 12 comment | 0 complexity | e627aa4eebbc3c55769c29f91bb4fd10 MD5 | raw file
 1"""
 2IT-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 _
 9from django.utils.encoding import smart_unicode
10from django.contrib.localflavor.it.util import ssn_check_digit, vat_number_check_digit
11import re
12
13class ITZipCodeField(RegexField):
14    default_error_messages = {
15        'invalid': _('Enter a valid zip code.'),
16    }
17    def __init__(self, *args, **kwargs):
18        super(ITZipCodeField, self).__init__(r'^\d{5}$',
19        max_length=None, min_length=None, *args, **kwargs)
20
21class ITRegionSelect(Select):
22    """
23    A Select widget that uses a list of IT regions as its choices.
24    """
25    def __init__(self, attrs=None):
26        from it_region import REGION_CHOICES
27        super(ITRegionSelect, self).__init__(attrs, choices=REGION_CHOICES)
28
29class ITProvinceSelect(Select):
30    """
31    A Select widget that uses a list of IT provinces as its choices.
32    """
33    def __init__(self, attrs=None):
34        from it_province import PROVINCE_CHOICES
35        super(ITProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES)
36
37class ITSocialSecurityNumberField(RegexField):
38    """
39    A form field that validates Italian Social Security numbers (codice fiscale).
40    For reference see http://www.agenziaentrate.it/ and search for
41    'Informazioni sulla codificazione delle persone fisiche'.
42    """
43    default_error_messages = {
44        'invalid': _(u'Enter a valid Social Security number.'),
45    }
46
47    def __init__(self, *args, **kwargs):
48        super(ITSocialSecurityNumberField, self).__init__(r'^\w{3}\s*\w{3}\s*\w{5}\s*\w{5}$',
49        max_length=None, min_length=None, *args, **kwargs)
50
51    def clean(self, value):
52        value = super(ITSocialSecurityNumberField, self).clean(value)
53        if value in EMPTY_VALUES:
54            return u''
55        value = re.sub('\s', u'', value).upper()
56        try:
57            check_digit = ssn_check_digit(value)
58        except ValueError:
59            raise ValidationError(self.error_messages['invalid'])
60        if not value[15] == check_digit:
61            raise ValidationError(self.error_messages['invalid'])
62        return value
63
64class ITVatNumberField(Field):
65    """
66    A form field that validates Italian VAT numbers (partita IVA).
67    """
68    default_error_messages = {
69        'invalid': _(u'Enter a valid VAT number.'),
70    }
71
72    def clean(self, value):
73        value = super(ITVatNumberField, self).clean(value)
74        if value in EMPTY_VALUES:
75            return u''
76        try:
77            vat_number = int(value)
78        except ValueError:
79            raise ValidationError(self.error_messages['invalid'])
80        vat_number = str(vat_number).zfill(11)
81        check_digit = vat_number_check_digit(vat_number[0:10])
82        if not vat_number[10] == check_digit:
83            raise ValidationError(self.error_messages['invalid'])
84        return smart_unicode(vat_number)