|
1 # -*- coding: utf-8 -*- |
|
2 """ |
|
3 PE-specific Form helpers. |
|
4 """ |
|
5 |
|
6 from django.core.validators import EMPTY_VALUES |
|
7 from django.forms import ValidationError |
|
8 from django.forms.fields import RegexField, CharField, Select |
|
9 from django.utils.translation import ugettext_lazy as _ |
|
10 |
|
11 class PERegionSelect(Select): |
|
12 """ |
|
13 A Select widget that uses a list of Peruvian Regions as its choices. |
|
14 """ |
|
15 def __init__(self, attrs=None): |
|
16 from pe_region import REGION_CHOICES |
|
17 super(PERegionSelect, self).__init__(attrs, choices=REGION_CHOICES) |
|
18 |
|
19 class PEDNIField(CharField): |
|
20 """ |
|
21 A field that validates `Documento Nacional de IdentidadŽ (DNI) numbers. |
|
22 """ |
|
23 default_error_messages = { |
|
24 'invalid': _("This field requires only numbers."), |
|
25 'max_digits': _("This field requires 8 digits."), |
|
26 } |
|
27 |
|
28 def __init__(self, *args, **kwargs): |
|
29 super(PEDNIField, self).__init__(max_length=8, min_length=8, *args, |
|
30 **kwargs) |
|
31 |
|
32 def clean(self, value): |
|
33 """ |
|
34 Value must be a string in the XXXXXXXX formats. |
|
35 """ |
|
36 value = super(PEDNIField, self).clean(value) |
|
37 if value in EMPTY_VALUES: |
|
38 return u'' |
|
39 if not value.isdigit(): |
|
40 raise ValidationError(self.error_messages['invalid']) |
|
41 if len(value) != 8: |
|
42 raise ValidationError(self.error_messages['max_digits']) |
|
43 |
|
44 return value |
|
45 |
|
46 class PERUCField(RegexField): |
|
47 """ |
|
48 This field validates a RUC (Registro Unico de Contribuyentes). A RUC is of |
|
49 the form XXXXXXXXXXX. |
|
50 """ |
|
51 default_error_messages = { |
|
52 'invalid': _("This field requires only numbers."), |
|
53 'max_digits': _("This field requires 11 digits."), |
|
54 } |
|
55 |
|
56 def __init__(self, *args, **kwargs): |
|
57 super(PERUCField, self).__init__(max_length=11, min_length=11, *args, |
|
58 **kwargs) |
|
59 |
|
60 def clean(self, value): |
|
61 """ |
|
62 Value must be an 11-digit number. |
|
63 """ |
|
64 value = super(PERUCField, self).clean(value) |
|
65 if value in EMPTY_VALUES: |
|
66 return u'' |
|
67 if not value.isdigit(): |
|
68 raise ValidationError(self.error_messages['invalid']) |
|
69 if len(value) != 11: |
|
70 raise ValidationError(self.error_messages['max_digits']) |
|
71 return value |
|
72 |