| 42 | |
| 43 | class BRCPFField(CharField): |
| 44 | def __init__(self, *args, **kwargs): |
| 45 | super(BRCPFField, self).__init__(max_length=11, *args, **kwargs) |
| 46 | |
| 47 | def clean(self, value): |
| 48 | super(BRCPFField, self).clean(value) |
| 49 | if value in EMPTY_VALUES: |
| 50 | return u'' |
| 51 | try: |
| 52 | int(value) |
| 53 | except ValueError: |
| 54 | raise ValidationError(gettext(u'The CPF field must contain only |
| 55 | numbers.')) |
| 56 | if self._validate_cpf(value): |
| 57 | return value |
| 58 | |
| 59 | def _validate_cpf(self, cpf): |
| 60 | if len(cpf) < 11: |
| 61 | raise ValidationError(gettext(u'Invalid CPF. The CPF field must |
| 62 | contain 11 digits.')) |
| 63 | number = 0 |
| 64 | for i,j in enumerate(range(10,1,-1)): |
| 65 | number += int(cpf[i])*j |
| 66 | if self._create_dv(number) <> cpf[9]: |
| 67 | raise ValidationError(gettext(u'Invalid CPF.')) |
| 68 | |
| 69 | number = 0 |
| 70 | |
| 71 | for i,j in enumerate(range(11,1,-1)): |
| 72 | number += int(cpf[i])*j |
| 73 | if self._create_dv(number) <> cpf[10]: |
| 74 | raise ValidationError(gettext(u'Invalid CPF.')) |
| 75 | return True |
| 76 | |
| 77 | def _create_dv(self, number): |
| 78 | if number % 11 > 1: |
| 79 | return str(11 - number % 11) |
| 80 | else: |
| 81 | return '0' |