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