2 IT-specific Form helpers
5 from __future__
import absolute_import
9 from django
.contrib
.localflavor
.it
.it_province
import PROVINCE_CHOICES
10 from django
.contrib
.localflavor
.it
.it_region
import REGION_CHOICES
11 from django
.contrib
.localflavor
.it
.util
import ssn_check_digit
, vat_number_check_digit
12 from django
.core
.validators
import EMPTY_VALUES
13 from django
.forms
import ValidationError
14 from django
.forms
.fields
import Field
, RegexField
, Select
15 from django
.utils
.translation
import ugettext_lazy
as _
16 from django
.utils
.encoding
import smart_unicode
19 class ITZipCodeField(RegexField
):
20 default_error_messages
= {
21 'invalid': _('Enter a valid zip code.'),
23 def __init__(self
, max_length
=None, min_length
=None, *args
, **kwargs
):
24 super(ITZipCodeField
, self
).__init
__(r
'^\d{5}$',
25 max_length
, min_length
, *args
, **kwargs
)
27 class ITRegionSelect(Select
):
29 A Select widget that uses a list of IT regions as its choices.
31 def __init__(self
, attrs
=None):
32 super(ITRegionSelect
, self
).__init
__(attrs
, choices
=REGION_CHOICES
)
34 class ITProvinceSelect(Select
):
36 A Select widget that uses a list of IT provinces as its choices.
38 def __init__(self
, attrs
=None):
39 super(ITProvinceSelect
, self
).__init
__(attrs
, choices
=PROVINCE_CHOICES
)
41 class ITSocialSecurityNumberField(RegexField
):
43 A form field that validates Italian Social Security numbers (codice fiscale).
44 For reference see http://www.agenziaentrate.it/ and search for
45 'Informazioni sulla codificazione delle persone fisiche'.
47 default_error_messages
= {
48 'invalid': _(u
'Enter a valid Social Security number.'),
51 def __init__(self
, max_length
=None, min_length
=None, *args
, **kwargs
):
52 super(ITSocialSecurityNumberField
, self
).__init
__(r
'^\w{3}\s*\w{3}\s*\w{5}\s*\w{5}$',
53 max_length
, min_length
, *args
, **kwargs
)
55 def clean(self
, value
):
56 value
= super(ITSocialSecurityNumberField
, self
).clean(value
)
57 if value
in EMPTY_VALUES
:
59 value
= re
.sub('\s', u
'', value
).upper()
61 check_digit
= ssn_check_digit(value
)
63 raise ValidationError(self
.error_messages
['invalid'])
64 if not value
[15] == check_digit
:
65 raise ValidationError(self
.error_messages
['invalid'])
68 class ITVatNumberField(Field
):
70 A form field that validates Italian VAT numbers (partita IVA).
72 default_error_messages
= {
73 'invalid': _(u
'Enter a valid VAT number.'),
76 def clean(self
, value
):
77 value
= super(ITVatNumberField
, self
).clean(value
)
78 if value
in EMPTY_VALUES
:
81 vat_number
= int(value
)
83 raise ValidationError(self
.error_messages
['invalid'])
84 vat_number
= str(vat_number
).zfill(11)
85 check_digit
= vat_number_check_digit(vat_number
[0:10])
86 if not vat_number
[10] == check_digit
:
87 raise ValidationError(self
.error_messages
['invalid'])
88 return smart_unicode(vat_number
)